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

前端 未结 8 2521
南旧
南旧 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 07:16

    ad 1. Yes. No.

    ad 2. Yes. No.

    Proof:

    async function start() 
    {
      console.log('Start');
    
      for (var i = 0; i < 10; ++i) {
        let result = await some_slow_async_function(i);
        do_something_with_result(i);
      }
      
      console.log('Finish');
    }
    
    function some_slow_async_function(n) {
      return new Promise(res => setTimeout(()=>{
        console.log(`Job done: ${(2000/(1+n))|0} ms`);
        res(true);
      },2000/(1+n)));
    }
    
    function do_something_with_result(n) {
      console.log(`Something ${n}`);
    }
    
    start();

提交回复
热议问题