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