console.log('script start')
async function async1() {
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2 end')
}
async1()
setTimeout(function() {
console.log('setTimeout')
}, 0)
new Promise(resolve => {
console.log('Promise')
resolve()
})
.then(function() {
console.log('promise1')
})
.then(function() {
console.log('promise2')
})
console.log('script end')
- 第 1 行是同步代码,输出
script start
。 - 第 10 行执行 async1,async1 中执行 async2,因此会输出
async2 end
。然后回到 async1,碰到 await 之后,暂停执行 async 1 中的代码,并将其中执行的代码扔进 job queue 中等待执行。 - 执行 12 行的 setTimeout,将其函数扔进 callback queue 中等待执行。
- 执行 16 行新建一个 Promise 对象,输出
Promise
,遇到 resolve() 之后,将后面两个 then 的函数扔进 job queue 中。 - 27 行中输出
script end
。
经过上面的步骤,已经输出的内容有 script start => async2 end => Promise => script end。
之后处理 job queue 中的函数,job queue 中的需要处理的代码有
- aync1 中的代码
console.log('async1 end')
- 两个 then 函数的回调。
另外 callback queue 中含有的代码时:
- setTimeout 中的回调函数。
因此之后的输出内容将会是 async1 end => promise1 => promise2 => script end。
因此将所有的数据结果结合起来,得到的将会是
// script start => async2 end => Promise => script end => script start
// => async2 end => Promise => script end