How is async/await working in serial and parallel?

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

    Because thesleep()function is a synchronous function, it just return a asynchronous promise, eg:

    function sleep (time) {
        return new Promise((resolve) => setTimeout(resolve, time));
    }
    

    In parallel(), the two sleep() synchronously init two promise,they wait to be resolved meanwhile, it's going to be about 3s.

    However, in serial(), the two await sleep() means that the second sleep() promise must wait for the first sleep() to be resolved, so it's going to be about 6s.

提交回复
热议问题