How is async/await working in serial and parallel?

后端 未结 3 1343
野性不改
野性不改 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

    Frxstream already has an excellent answer. To build on that, and provide some perspective:

    The first thing to recognize is that Promises are created "hot" - that is, by the time you have a promise object, it is already "in progress".

    The second important concept is that await is like an "asynchronous wait" - that is, it pauses the execution of the function until that promise completes.

    So, the serial function calls sleep, gets a promise back, and then (asynchronously) waits for that promise to complete. After that promise completes 3 seconds later, serial again calls sleep, gets a promise back, and then (asynchronously) waits for that promise to complete. After that promise completes 3 seconds later, serial completes.

    The parallel function calls sleep and stores its promise in a, and then calls sleep and stores its promise in b, and then (asynchronously) waits for a to complete. After a completes 3 seconds later, parallel (asynchronously) waits for b to complete. After b completes practically immediately, parallel completes.

提交回复
热议问题