# 此题坑在与:await后面创建一个异步微任务,
只有等到await后面的promise实例的状态是fulfilled成功之后,await后面创建的异步微任务代码才可以执行,不然就阻塞无法执行,
本题await后new Promise实例的状态一直是pending状态的,
所以 console.log('async1 end'); return 'async1 success'无法执行到这里。
const async1 = async () => {
console.log('async1');
setTimeout(() => {
console.log('timer1')
}, 2000)
await new Promise(resolve => { # promise的状态是pending的
console.log('promise1')
})
console.log('async1 end')
return 'async1 success'
}
console.log('script start');
async1().then(res => console.log(res)); // promise的状态不是成功执行不到then中
console.log('script end');
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.catch(4)
.then(res => console.log(res)) // 穿透了
setTimeout(() => {
console.log('timer2')
}, 1000)
'script start'
'async1'
'promise1'
'script end'
1
'timer2'
'timer1'
# 改版1
const async1 = async () => {
console.log('async1');
setTimeout(() => {
console.log('timer1')
}, 2000)
await new Promise(resolve => {
console.log('promise1')
resolve() // 新加
})
console.log('async1 end')
return 'async1 success'
}
console.log('script start');
async1().then(res => console.log(res));
console.log('script end');
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.catch(4)
.then(res => console.log(res))
setTimeout(() => {
console.log('timer2')
}, 1000)
script start
async1
promise1
script end
async1 end
async1 success
1
timer2
timer1
# 改版2
const async1 = async () => {
console.log('async1');
setTimeout(() => {
console.log('timer1')
}, 2000)
new Promise(resolve => { // 去掉await
console.log('promise1')
resolve()
})
console.log('async1 end')
return 'async1 success'
}
console.log('script start');
async1().then(res => console.log(res));
console.log('script end');
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.catch(4)
.then(res => console.log(res))
setTimeout(() => {
console.log('timer2')
}, 1000)
script start
async1
promise1
async1 end
script end
async1 success
1
timer2
timer1
JavaScript 同步异步(微任务、宏任务)代码执行顺序 - 2
于 2022-01-26 15:22:05 首次发布