在JavaScript中,在循环中使用`await`阻塞循环吗? [英] In JavaScript, does using `await` inside a loop block the loop?

查看:248
本文介绍了在JavaScript中,在循环中使用`await`阻塞循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采取以下循环:

for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}




  1. 等待阻止循环?或 i 继续增加,而等待 ing?

  1. Does await block the loop? Or does the i continue to be incremented while awaiting?

的顺序是do_something_with_result()保证顺序 i ?或者它取决于每个 i await ed函数的速度有多快?

Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?


推荐答案



  1. 等待阻止循环?或 i 继续增加,而等待 ing?

  1. Does await block the loop? Or does the i continue to be incremented while awaiting?


阻止不是正确的词,但是,是的, i 在等待时不会继续增加。而是执行跳回到调用 async 函数的位置,提供一个promise作为返回值,继续函数调用后的其余代码,直到代码堆栈已被清空。然后当等待结束时,恢复功能的状态,并在该功能内继续执行。每当该函数返回(完成)时,相应的承诺 - 先前返回的 - 将被解决。

"Block" is not the right word, but yes, i does not continue to be incremented while awaiting. Instead the execution jumps back to where the async function was called, providing a promise as return value, continuing the rest of the code that follows after the function call, until the code stack has been emptied. Then when the awaiting is over, the state of the function is restored, and execution continues within that function. Whenever that function returns (completes), the corresponding promise -- that was returned earlier on -- is resolved.



  1. 的顺序是do_something_with_result()关于 i 的保证顺序?或者它取决于每个 i await ed函数的速度有多快?

  1. Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?


订单有保证。 await 之后的代码也保证仅在调用堆栈清空后执行,即至少在下一个微任务执行时或之后执行。

The order is guaranteed. The code following the await is also guaranteed to execute only after the call stack has been emptied, i.e. at least on or after the next microtask can execute.

查看此代码段中的输出结果。请特别注意调用测试后:

See how the output is in this snippet. Note especially where it says "after calling test":

async function test() {
    for (let i = 0; i < 2; i++) {
        console.log('Before await for ', i);
        let result = await Promise.resolve(i);
        console.log('After await. Value is ', result);
    }
}

test().then(_ => console.log('After test() resolved'));

console.log('After calling test');

这篇关于在JavaScript中,在循环中使用`await`阻塞循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆