Promise、事件循环试题一
写出下面代码的执行顺序:
setTimeout(function () {
console.log("setTimeout1");
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("promise1");
resolve();
}).then(function () {
console.log("then1");
});
setTimeout(function () {
console.log("setTimeout2");
});
console.log(2);
queueMicrotask(() => {
console.log("queueMicrotask1")
});
new Promise(function (resolve) {
resolve();
}).then(function () {
console.log("then3");
});
分析:
// 全局代码打印
// promise1
// 2
// 宏任务队列的函数
// 1.第一个函数
setTimeout(function () {
console.log("setTimeout1");
new Promise(function (resolve) {
resolve();
}).then(function () {
new Promise(function (resolve) {
resolve();
}).then(function () {
console.log("then4");
});
console.log("then2");
});
});
// 2.第二个函数
setTimeout(function () {
console.log("setTimeout2");
});
// 微任务队列的函数
// 1.第一个函数 下面这个Promise中的then方法的回调
new Promise(function (resolve) {
console.log("promise1");
resolve();
}).then(function () {
console.log("then1");
});
// 2.queueMicrotask函数
queueMicrotask(() => {
console.log("queueMicrotask1")
});
// 3.第三个函数 下面这个Promise中的then方法的回调
new Promise(function (resolve) {
resolve();
}).then(function () {
console.log("then3");
});
// 全局代码打印
// promise1
// 2
// 微任务队列第一次打印
// then1
// queueMicrotask1
// then3
// 全局代码打印
// promise1
// 2
// 微任务队列第一次打印
// then1
// queueMicrotask1
// then3
// 宏任务队列第一次打印
// setTimeout1
// then2
// 宏任务队列的函数
// 1.第一个函数
setTimeout(function () {
console.log("setTimeout2");
});
// 微任务队列的函数
// 1.第一个函数
function () {
new Promise(function (resolve) {
resolve();
}
// 2.第二个函数
function () {
console.log("then4");
}
// 全局代码打印
// promise1
// 2
// 微任务队列第一次打印
// then1
// queueMicrotask1
// then3
// 宏任务队列第一次打印
// setTimeout1
// then2
// 微任务队列第二次打印
// then4
// 全局代码打印
// promise1
// 2
// 微任务队列第一次打印
// then1
// queueMicrotask1
// then3
// 宏任务队列第一次打印
// setTimeout1
// then2
// 微任务队列第二次打印
// then4
// 宏任务队列第二次打印
// setTimeout2
Promise、事件循环试题二
同样写出下面代码的打印顺序, 思路和上面一样
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