In JavaScript, does using await inside a loop block the loop?

前端 未结 8 2566
南旧
南旧 2020-12-02 06:38

Take the following loop:

for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}
8条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 06:58

    As @realbart says, it does block the loop, which then will make the calls sequential.

    If you want to trigger a ton of awaitable operations and then handle them all together, you could do something like this:

    const promisesToAwait = [];
    for (let i = 0; i < 100; i++) {
      promisesToAwait.push(fetchDataForId(i));
    }
    const responses = await Promise.all(promisesToAwait);
    

提交回复
热议问题