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')
script start 同步代码
async2 end
Promise
script end
async1 end
promise1
promise2
setTimeout
console.log('script start') 立即执行 1
async function async1() {
await async2()
console.log('async1 end') 异步队列 1 微任务
}
async function async2() {
await console.log('async2 end') 立即执行 2
}
async1()
setTimeout(function() {
console.log('setTimeout') 异步队列 1 宏任务
}, 0)
new Promise(resolve => {
console.log('Promise') 立即执行 3
resolve()
})
.then(function() {
console.log('promise1') 异步队列 1 微任务
})
.then(function() {
console.log('promise2')
})
console.log('script end') 立即执行 4
script start
async2 end
Promise
script end
promise1
async1 end
promise2
setTimeout
new Promise((r,j) => {
r();
}).then(() => {
console.log(1);
Promise.resolve().then(() => {
console.log(3)
Promise.resolve().then(() => {
console.log(4)
Promise.resolve().then(() => {
console.log(5)
})
})
})
}).then(() => {
console.log(2);
})
// 1 3 2 4 5
Promise.resolve().then(() => {
console.log('promise1');
const timer2 = setTimeout(() => {
console.log('timer2')
}, 0)
});
const timer1 = setTimeout(() => {
console.log('timer1')
Promise.resolve().then(() => {
console.log('promise2')
})
}, 0)
console.log('start');
// start promise1 timer1 promise2 timer2、
最大宏任务 script
之后 Promise 异步微任务 Promise.then script宏任务下的微任务队列
之后 setTimeout 异步宏任务 setTimeout script宏任务下的宏任务任务队列
Promise.then 下有 setTimeout宏任务
setTimeout 下有 Promise.then 微任务
依照先执行 宏任务下的所有微任务,之后执行下一个宏任务 即
script
Promise.then
timer1
timer1>Promise.resolve
timer2