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

问题描述

进行以下循环:

for(var i=0; i
  1. await 会阻塞循环吗?还是 iawaiting 时继续递增?

  2. do_something_with_result() 的顺序是否保证相对于 i 是连续的?还是取决于 awaited 函数对于每个 i 的速度有多快?

解决方案

"Block" 不是正确的词,但是是的,i 在等待时不会继续递增.相反,执行会跳回到 async 函数被调用的地方,提供一个 promise 作为返回值,继续执行函数调用之后的其余代码,直到代码堆栈被清空.然后当等待结束时,恢复函数的状态,并在该函数内继续执行.每当该函数返回(完成)时,相应的承诺——之前返回的——就会被解析.

  1. do_something_with_result() 的顺序是否保证相对于 i 是连续的?还是取决于 awaited 函数对于每个 i 的速度有多快?

订单有保障.await 后面的代码也保证只有在调用堆栈被清空后才会执行,即至少在下一个微任务可以执行时或之后执行.

看看这个片段中的输出如何.特别注意它说在调用测试之后":

async function test() {for (让 i = 0; i  console.log('After test() 解决'));console.log('调用测试后');

Take the following loop:

for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}
  1. Does await block the loop? Or does the i continue to be incremented while awaiting?

  2. 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?

解决方案

"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.

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 会阻塞循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:59