javascript事件循环机制及面试题详解
javascript事件循环机制及面试题详解

new Promise(resolve => {
console.log('promise');
resolve(5);
}).then(value=>{
console.log('then回调', value)
})
function func1() {
console.log('func1');
}
setTimeout(() => {
console.log('setTimeout');
});
func1();
创建一个promise的实例就是开启了一个异步任务,传入的回调函数,也叫做excutor 函数,会立刻执行,所以输入promise,使用resolve返回一个成功的执行结果,then函数里的执行会推入到微任务队列中等待调用栈执行完成才依次执行。
setTimeout(function () {
console.log("set1");
new Promise(function (resolve) {
resolve();
}).then(function () {
new Promise(function (resolve) {
resolve();
}).then(function () {
console.log("then4");
});
console.log("then2");
});
});
new Promise(function (resolve) {
console.log("pr1");
resolve();
}).then(function () {
console.log("then1");
});
setTimeout(function () {
console.log("set2");
});
console.log(2);
queueMicrotask(() => {
console.log("queueMicrotask1")
});
new Promise(function (resolve) {
resolve();
}).then(function () {
console.log("then3");
});
setTimeout执行的回调函数("set1")直接被放置到宏任务队列中等待,Promise的excutor函数立刻执行,首先输入 pr1,Promise.then函数("then1")放入微任务队列中等待,下面的setTimeout执行的回调函数("set2")也被放置到宏任务队列中,排在("set1")后面,接下来调用栈中输出2,queueMicrotask表示开启一个微任务,与Promise.then函数效果一致,("queueMicrotask1")放入微任务队列中,再往下执行,new Promise的excutor函数立刻执行,then函数("then3")放到微任务队列中等待,此时调用栈出已依次输入pr1,2。
pr1 2 then1 queueMicrotask1 then3 set1 then2 then4 set2
简单图示如下

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')
函数只有调用的时候才会推入调用栈中,所以最先执行的是 console.log,即输出 script start,然后setTimeout函数("setTimeout")放入宏任务队列中等待,调用async1函数,输出 async1 start,执行async2函数,输出async2,("async1 end")放入微任务队列中等待,继续向下执行Promise函数,输出 promise1,then函数中的("promise2")放入微任务队列中等待,输出 script end。
script start async1 start async2 promise1 script end async1 end promise2 setTimeout
简单图示如下


浙公网安备 33010602011771号