我正在学习微任务队列,我有一个简单的问题。
使用以下代码:
Promise.resolve().then(()=>console.log("Resolved1 Promise"));
Promise.reject().then(()=>console.log("Resolved2 Promise")).catch(()=>console.log('Rejected2 Promise'));
Promise.resolve().then(()=>console.log("Resolved3 Promise"));
Promise.resolve().then(()=>console.log("Resolved4 Promise"));
Promise.resolve().then(()=>console.log("Resolved5 Promise"));
我期望输出按顺序排列:
Resolved1 Promise
Rejected2 Promise
Resolved3 Promise
Resolved4 Promise
Resolved5 Promise
但是正如您可以在上面尝试的那样,最后会触发拒绝的回调。谁能给我解释一下吗?
这是因为 JavaScript 的内部计时,并且是由具有
.then()
和 .catch()
回调的第二个承诺(拒绝的承诺)引起的。这可以通过从承诺中删除 .then()
来解决:
Promise.resolve().then(() => console.log("Resolved1 Promise"));
Promise.reject().catch(() => console.log('Rejected2 Promise'));
Promise.resolve().then(() => console.log("Resolved3 Promise"));
Promise.resolve().then(() => console.log("Resolved4 Promise"));
Promise.resolve().then(() => console.log("Resolved5 Promise"));
如果您想监听这两个事件,请使用单个
.then()
调用来分配两个监听器:
Promise.resolve().then(() => console.log("Resolved1 Promise"));
Promise.reject().then(
() => console.log("Resolved2 Promise"),
() => console.log('Rejected2 Promise')
);
Promise.resolve().then(() => console.log("Resolved3 Promise"));
Promise.resolve().then(() => console.log("Resolved4 Promise"));
Promise.resolve().then(() => console.log("Resolved5 Promise"));