使用 Promise.reject() 拒绝 Promise 的序列

问题描述 投票:0回答:1

我正在学习微任务队列,我有一个简单的问题。

使用以下代码:

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 es6-promise asynchronous-javascript
1个回答
0
投票

这是因为 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"));

© www.soinside.com 2019 - 2024. All rights reserved.