async-thread-worker
async-thread-worker copied to clipboard
async/await functions inside nodejs ThreadWorker
Hello. Is it possible to use async/await functions inside nodejs ThreadWorker?
Yes! I have just added such an example (see https://github.com/w3reality/async-thread-worker/blob/master/examples/node/simple.js).
thanks, but what if I need the main script to not use "wait" and wait for a response? and the data from threads came already after sending of all messages in threads?
result.push(**await** th.sendRequest(payload));
what if I need the main script to not use
awaitand wait for a response?
I think that you can keep the Promise's returned by th.sendRequest(payload), and later, access each result however you like, e.g.
const result = [];
for (let payload of ['a', 'b', 'c', 'd']) {
result.push(th.sendRequest(payload));
}
setTimeout(() => { // wait for the thread to finish sending all the messages
result[2].then(x => console.log(x)); // C
result[1].then(x => console.log(x)); // B
th.terminate();
}, 8000);