for await of VS Promise.all

前端 未结 3 2269
情深已故
情深已故 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:48

    As you said Promise.all will send all the requests in one go and then you will get the response when all of them gets completed.

    In the second scenario, you will send the request in one go but recieve response as for each one by one.

    See this small example for reference.

    let i = 1;
    function somethingAsync(time) {
      console.log("fired");
      return delay(time).then(() => Promise.resolve(i++));
    }
    const items = [1000, 2000, 3000, 4000];
    
    function delay(time) {
      return new Promise((resolve) => { 
          setTimeout(resolve, time)
      });
    }
    
    (async() => {
      console.time("first way");
      const promises = await Promise.all(items.map(e => somethingAsync(e)));
      for (const res of promises) {
        console.log(res);
      }
      console.timeEnd("first way");
    
      i=1; //reset counter
      console.time("second way");
      for await (const res of items.map(e => somethingAsync(e))) {
        // do some calculations
        console.log(res);
      }
      console.timeEnd("second way");
    })();
    
    

    You could try it here as well - https://repl.it/repls/SuddenUselessAnalyst

    Hope this helps.

提交回复
热议问题