本次内容将会有两个题目,会给出代码、结果、过程。要将这三个题目对比来看,找到其中的不同之处,这样会更有利于理解相应的知识点。
另外在此之前要先弄清楚await在事件循环中有什么作用(promise相对简单这里不做过多解释):当await完成后它会将后面的代码推入到微队列中,如果后面没有代码就会将 “xx函数完成”这个事件推入到微队列(这个函数就是await所在的函数)。
这里可能不太好理解,请结合代码进行思考。
一、例题1
async function foo() {
console.log("foo")
}
async function bar() {
console.log("bar start")
await foo()
console.log("bar end")
}
console.log("script start")
setTimeout(function () {
console.log("setTimeout")
}, 0)
bar()
new Promise(function (resolve) {
console.log('promise start')
resolve()
}).then(function () {
console.log('promise end')
})
console.log("script end")
运行结果:
过程分析:
二、例题2
async function asy1() {
console.log(1)
await asy2()
console.log(2)
}
const asy2 =async () => {
await setTimeout(() => {
Promise.resolve().then(() => {
console.log(3)
});
console.log(4)
})
}
const asy3 = async () => {
Promise.resolve().then(() => {
console.log(6)
});
}
asy1()
console.log(7)
asy3()
运行结果:
过程分析: