for await of VS Promise.all

前端 未结 3 2299
情深已故
情深已故 2020-12-11 01:50

Is there any difference between this:

const promises = await Promise.all(items.map(e => somethingAsync(e)));
for (c         


        
3条回答
  •  情歌与酒
    2020-12-11 02:29

    Actually, using the for await syntax does fire the promises all at once.

    The small piece of code proves it:

    const sleep = s => {
      return new Promise(resolve => {
        setTimeout(resolve, s * 1000);
      });
    }
    
    const somethingAsync = async t => {
      await sleep(t);
      return t;
    }
    
    (async () => {
      const items = [1, 2, 3, 4];
      const now = Date.now();
      for await (const res of items.map(e => somethingAsync(e))) {
        console.log(res);
      }
      console.log("time: ", (Date.now() - now) / 1000);
    })();
    

    stdout: time: 4.001

    But the inside of the loop doesn't act "as a callback". If I reverse the array, all the logs appear at once. I suppose that the promises are fired at once and the runtime just waits for the first one to resolve to go to the next iteration.

    EDIT: Actually, using for await is bad practice when we use it with something other than an asynchronous iterator, best is to use Promise.all, according to @Bergi in his answer.

提交回复
热议问题