简体   繁体   中英

Using Javascript Web Worker and Async together?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM