How is async/await working in serial and parallel?

后端 未结 3 1354
野性不改
野性不改 2021-02-14 14:45

I have two async functions. Both of them are waiting for two 3 seconds function calls. But the second one is faster than the first. I think the faster one is runnin

3条回答
  •  一整个雨季
    2021-02-14 15:16

    It's clearer if you write your serial function like this:

    async function serial() {
      var a = sleep(); //
      await a;         // await sleep();
    
      var b = sleep(); //
      await b;         // await sleep();
    }
    
    async function parallel() {
      var a = sleep();
      var b = sleep();
      await a;
      await b;
    }
    

    Here you can clearly see that in the serial function, the second sleep() is only called after the first sleep() has completed, while in parallel it's called immediately, before the first has completed, and then it waits for both to complete. So while they may look functionally identical, they are subtly different.

提交回复
热议问题