async-thread-worker icon indicating copy to clipboard operation
async-thread-worker copied to clipboard

async/await functions inside nodejs ThreadWorker

Open ser0ja opened this issue 2 years ago • 3 comments

Hello. Is it possible to use async/await functions inside nodejs ThreadWorker?

ser0ja avatar Jan 22 '23 12:01 ser0ja

Yes! I have just added such an example (see https://github.com/w3reality/async-thread-worker/blob/master/examples/node/simple.js).

j-devel avatar Jan 24 '23 01:01 j-devel

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));

ser0ja avatar Jan 24 '23 11:01 ser0ja

what if I need the main script to not use await and 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);

j-devel avatar Jan 25 '23 10:01 j-devel