简体   繁体   English

将 Javascript Web Worker 和 Async 一起使用?

[英]Using Javascript Web Worker and Async together?

Does anyone used Web Worker and Async together or does anyone vote against this?有没有人一起使用 Web Worker 和 Async 或者有人投票反对这个?

For example, if I want to send out 1000 async calls and wait for them to finish, it is synchronous, so, it is slow.例如,如果我想发送 1000 个异步调用并等待它们完成,它是同步的,所以它很慢。 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).我可以等待一个创建 1000 个 Web Workers 并并行发送 1000 个提取(每个工作一个提取)的异步方法。 And each web worker will wait for the fetch result and post the result back.每个 web 工作人员将等待获取结果并将结果返回。 And on the main async method that created 1000 Web Workers, it collects all 1000 results.在创建 1000 个 Web Workers 的主要异步方法上,它收集了所有 1000 个结果。 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.您不需要工作人员,因为fetch不会阻塞主线程。 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.默认情况下, fetch已经做了你想要的,你不应该等待每一个调用。

You can use Promise.allSettled to convert an array of promises to a single promise of results that you can then await .您可以使用Promise.allSettled将一组 promise 转换为单个 promise 结果,然后您可以await

const promises = urls.map(url => fetch(url));
const results = await Promise.allSettled(promises);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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