在JavaScript中,在循环内使用await是否会阻塞循环? [英] In JavaScript, does using await inside a loop block the loop?

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

问题描述

执行以下循环:

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

  1. await是否阻塞循环?还是在await ing期间i继续增加?

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

相对于ido_something_with_result()的顺序是否保证是连续的?还是取决于每个iawait 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. await是否阻塞循环?还是在await期间i继续递增?
  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. 相对于ido_something_with_result()的顺序是否保证是连续的?还是取决于每个iawait 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天全站免登陆