繁体   English   中英

没有自定义等待的并行异步调用 function

[英]Parallel async calls without custom await function

我想使用异步 function 并行运行一个循环。 所以我尝试了:

 let counters = [0,0] const calc = async(x) => { for(let i=0; i<10; i+=1) { counters[x]+=1; console.log(counters[0], counters[1]); } } calc(0) calc(1)

经过这次尝试,我发现如果在 function 中等待,则在终止之前,异步 function 调用实际上是为下一个 function 调用释放的。

所以,我修改了 function 并且它可以工作:

 let counters = [0,0] const delay = () => new Promise(resolve=>resolve()) const calc = async(x) => { for(let i=0; i<10; i+=1){ await delay() counters[x]+=1; console.log(counters[0],counters[1]); } } calc(0) calc(1)

但是,这种延迟与循环的逻辑不一致。 那么,有没有办法在没有它的情况下运行循环辅助拉力赛?

async函数和await允许您编写异步代码,就好像是顺序的。 这意味着代码被迫通过await返回事件循环来一个接一个地执行异步操作,直到知道其操作数 promise 的确定命运。

await的全部意义在于编码以顺序步骤获取数据结果,这与并行处理相反 - 您不能在同一个async function 中并行启动两个await操作。

If you want parallel operation of asynchronous processes, create an array of promises, one for each individual operation result (eg by using the promise returned from calling an async function which performs a single operation) and using one of the static Promise methods, such as allracesettled处理并行获得的结果。

暂无
暂无

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

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