【发布时间】:2021-04-09 07:50:30
【问题描述】:
为什么setTimout() 优先于承诺?请看下面的两个例子。据我所知,Promise 是有优先级的,也就是说,Promise 会在setTimeout() 之前执行。这在下面的第一个示例中得到了证明。
console.log("First");
setTimeout(() => console.log("Second"), 0);
console.log("Third");
const promise = new Promise(function (resolve, reject) {
resolve("Forth");
reject(new Error("Rejected"));
});
promise.then((res) => console.log(res)).catch((err) => console.log(err));
//output:
//"First"
//"Third"
//"Forth"
//"Second"
但是如果我们在 Promise 中有 setTimeout(),它将不再被优先考虑。不再是承诺了吗?为什么它会这样?第二个示例不应该与第一个示例具有相同的输出吗?
console.log("First");
setTimeout(() => console.log("Second"), 0);
console.log("Third");
const promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Forth");
reject(new Error("Rejected"));
}, 0);
});
promise.then((res) => console.log(res)).catch((err) => console.log(err));
//"First"
//"Third"
//"Second"
//"Forth"
【问题讨论】:
标签: javascript promise settimeout v8