X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=lib%2Fworkers.js;h=abd60b4ff0ba814aac9d0af43cd4a5f7fe34d31b;hb=695b7a99868082d63ab01c0946ca8d19f63ba27a;hp=103061aa78b55e55625eb877f81b300239116d14;hpb=8950a9413daaff104bdfe23de5331ff744ee883b;p=poolifier.git diff --git a/lib/workers.js b/lib/workers.js index 103061aa..abd60b4f 100644 --- a/lib/workers.js +++ b/lib/workers.js @@ -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