根据规范,事件循环时通过任务队列的机制来进行协调的。
//请写出输出内容
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
*/
// Learn from: https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/7
--- N --> 浏览器渲染 -> 下一个宏任务
|
宏任务 -> 执行结束 -> 有微任务? --
|
--- Y --> 执行所有微任务 -> 浏览器渲染 -> 下一个宏任务
new Promise((resolve, reject) => {
console.log(1)
reject(2)
console.log(2) // 会被输出
})
.then(() => console.log(3))
.catch(() => console.log(4))
.then(() => {
console.log(5)
Promise.reject().catch(() => console.log('5-1'))
})
.catch(() => console.log(6))
.then(() => {
console.log(7)
new Promise((resolve, reject) => {
console.log(8)
resolve()
})
.then(() => console.log(9))
.then(() => console.log(10))
Promise.resolve().then(() => console.log('promise.resolve'))
// 有没有 return 结果是一样的
return new Promise((resolve, reject) => {
console.log(11)
reject()
})
.then(() => console.log(12))
.catch(() => console.log(13))
.then(() => console.log(15))
})
.catch(() => console.log(16))
.then(() => console.log(17))
// 1
// 2
// 4
// 5
// 5-1
// 7
// 8
// 11
// 9
// promise.resolve
// 10
// 13
// 15
// 17