[feat] support exec async func in worker threads
[poolifier.git] / lib / workers.js
index 103061aa78b55e55625eb877f81b300239116d14..001c932ae7a92994b46f2a3e260a2affd337f87f 100644 (file)
@@ -16,6 +16,7 @@ class ThreadWorker extends AsyncResource {
     super('worker-thread-pool:pioardi')
     this.opts = opts || {}
     this.maxInactiveTime = this.opts.maxInactiveTime || (1000 * 60)
+    this.async = !!this.opts.async
     this.lastTask = Date.now()
     if (!fn) throw new Error('Fn parameter is mandatory')
     // keep the worker active
@@ -27,7 +28,11 @@ class ThreadWorker extends AsyncResource {
       if (value && value.data && value._id) {
         // here you will receive messages
         // console.log('This is the main thread ' + isMainThread)
-        this.runInAsyncScope(this._run.bind(this), this, fn, value)
+        if (this.async) {
+          this.runInAsyncScope(this._runAsync.bind(this), this, fn, value)
+        } else {
+          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
@@ -56,6 +61,16 @@ class ThreadWorker extends AsyncResource {
       this.lastTask = Date.now()
     }
   }
+
+  _runAsync(fn, value) {
+    fn(value.data).then(res => {
+      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