答案在最后,持续更新。
事件循环执行顺序为:
先执行宏任务script,并执行里面的同步任务;执行栈为空后查询是否存在微任务,存在就立即执行,然后开始下一轮的事件循环。
一
setTimeout(function () {
console.log(1);
});
new Promise(function(resolve,reject){
console.log(2)
resolve(3)
}).then(function(val){
console.log(val);
})
console.log(4);
二
setTimeout(function () {
const c = new Promise(function (resolve, reject) {
console.log(1);
resolve()
})
c.then(() => {
console.log(2);
})
console.log(3);
}, 1000);
const cc = new Promise((resolve, reject) => {
console.log(5);
resolve()
}).then(() => {
setTimeout(function () {
console.log(6);
}, 0)
return 7
}).then(d => {
console.log(d);
})
console.log(4);
三
console.log(1);
setTimeout(function () {
console.log(2);
}, 0);
new Promise(function (resolve) {
console.log(3);
resolve(Date.now());
}).then(function () {
console.log(4);
});
console.log(5);
setTimeout(function () {
new Promise(function (resolve) {
console.log(6);
resolve(Date.now());
}).then(function () {
console.log(7);
});
}, 0);
四
setTimeout(() => {
console.log('A');
}, 0);
var obj = {
func: function () {
setTimeout(function () {
console.log('B')
}, 0);
return new Promise(function (resolve) {
console.log('C');
resolve();
})
}
};
obj.func().then(function () {
console.log('D')
});
console.log('E');
五
async function async1() {
console.log('2');
await async2();
console.log('6')
}
async function async2() {
console.log('3')
}
console.log('1');
setTimeout(function () {
console.log('8')
}, 0);
async1();
new Promise(function (resolve) {
console.log('4');
resolve()
}).then(function () {
console.log('7')
});
console.log('5')
答案:
一:2,4,3,1
二:5,4,7,6,1,3,2
三:1,3,5,4,2,6,7
四:C,E,D,A,B
五:1,2,3,4,5,6,7,8
|