Fix problem in node 13.x version
[poolifier.git] / lib / workers.js
index ee03778d47d603711ee16e6b994e5955a49855d7..103061aa78b55e55625eb877f81b300239116d14 100644 (file)
@@ -27,9 +27,7 @@ class ThreadWorker extends AsyncResource {
       if (value && value.data && value._id) {
         // here you will receive messages
         // console.log('This is the main thread ' + isMainThread)
-        const res = this.runInAsyncScope(fn, null, value.data)
-        this.parent.postMessage({ data: res, _id: value._id })
-        this.lastTask = Date.now()
+        this.runInAsyncScope(this._run.bind(this), this, fn, value)
       } else if (value.parent) {
         // save the port to communicate with the main thread
         // this will be received once
@@ -37,6 +35,7 @@ class ThreadWorker extends AsyncResource {
       } else if (value.kill) {
         // here is time to kill this thread, just clearing the interval
         clearInterval(this.interval)
+        this.emitDestroy()
       }
     })
   }
@@ -46,6 +45,17 @@ class ThreadWorker extends AsyncResource {
       this.parent.postMessage({ kill: 1 })
     }
   }
+
+  _run (fn, value) {
+    try {
+      const res = fn(value.data)
+      this.parent.postMessage({ data: res, _id: value._id })
+      this.lastTask = Date.now()
+    } catch (e) {
+      this.parent.postMessage({ error: e, _id: value._id })
+      this.lastTask = Date.now()
+    }
+  }
 }
 
 module.exports.ThreadWorker = ThreadWorker