Xue case caused by A question, today A friend sent A question, ask first print A or print B

async function A(){
await setTimeout(() = >{
console.log('AAAA')
return
},2000);
}
async function B(){
await  setTimeout(() = >{
console.log('BBBB')},1000);
}
async function C(){
await A()
await B()
}
C()
Copy the code

Let’s start with the answer

Does this not async at first glance? Is this not await? Print A first and then B.

Async is placed in front of a function as a keyword, indicating that the function is an asynchronous function, which means that the execution of the function does not block the execution of subsequent code

Await is to wait for a Promise object. It can only be used in async function, otherwise an error will be reported. The return value is not a Promise object but the result of processing the Promise object. Await expression suspends execution of the current async function until the Promise processing is complete. This is a big pity. If the Promise is fulfilled normally, the resolve function parameter of its callback will be treated as the value of await expression, and async function will continue to be executed. If the Promise promises the exception (rejected), Await expressions throw the Promise exception cause. If the value of the expression after the await operator is not a Promise, the value will be converted to a normally processed Promise.

“Await” is added before setTimeout and not inside. SetTimeout is synchronous so it is not affected. SetTimeout will be added to the timer thread and when the timer ends, the function will be executed. The short time set by setTimeout is executed first.


And you think that’s the end of it? In return, I gave him a question. As follows.

  async function a() {
    return setTimeout(() = > { console.log('aaaaa')},2000);
  }
  async function b() {
    return setTimeout(() = > { console.log('bbbbb')},1000);
  }
  function c() {
    console.log(setTimeout(() = > { console.log('ccccc')},2000));
    console.log(setTimeout(() = > { console.log('ddddd')},2000));
    a().then(res= > (console.log(res)))
    console.log("@");
    b().then(res= > (console.log(res)))
  }
  c()
Copy the code

On the first answer

Return a setTimeout will have a return value, and the return value of these numbers is the return value of setTimeout, as well as the sequence to be executed. SetTimeout is executed sequentially in function C.

So let’s talk about this at sign. Why is @ executed before 3 on line 4 of function C? Because a().then() b().then() is a promise, and promises are added to the microtask queue first, while @ is executed first in the main thread.

Then setTimeout will be executed in accordance with the short set time first, and the same time will be executed in order, and the result as shown in the figure