Does anyone used Web Worker and Async together or does anyone vote against this?
For example, if I want to send out 1000 async calls and wait for them to finish, it is synchronous, so, it is slow. While it doesn't block the main thread, it is slow to do await one by one.
Can I wait on a single async method that creates 1000 Web Workers and sends out the 1000 fetches in parallel (one fetch per worker). And each web worker will wait for the fetch result and post the result back. And on the main async method that created 1000 Web Workers, it collects all 1000 results. Once done, it finishes the method and the main thread will continue from there?
I am not seeing examples out there. I am wondering why. Is this a bad idea? Or maybe there is a framework for it?
Thanks
You don't need workers since fetch
doesn't block the main thread. On top of that there would be a significant overhead.
fetch
already does what you want by default, you should simply not await every single call.
You can use Promise.allSettled
to convert an array of promises to a single promise of results that you can then await
.
const promises = urls.map(url => fetch(url));
const results = await Promise.allSettled(promises);