# ❓异步笔试题

请写出下面代码的运行结果

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
  console.log("async2");
}
console.log("script start");
setTimeout(function() {
  console.log("setTimeout");
}, 0);
async1();
new Promise(function(resolve) {
  console.log("promise1");
  resolve();
}).then(function() {
  console.log("promise2");
});
console.log("script end");

// 正确答案
// script start
// async1 start
// async2
// promise1
// script end
// async1 end
// promise2
// setTimeout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

这里需要注意的是:

async function async1() {
  console.log("async1 start");
  // 这里遇到await会先执行一遍后面的表达式。
  // 让出执行线程,遇到异步返回,推入微任务队列
  // 跳出当前执行,继续往下执行
  await async2();
  console.log("async1 end");
}

// 会先执行一次 async2
// 我们知道 async 函数返回的是 Promise 对象,同时 async 函数内部 return 语句返回的值,会成为 then 方法回调函数的参数。
// 这里返回 Promise { undefined }
// 微任务,被加入微任务队列
async function async2() {
  console.log("async2");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16