问题描述
我在链接 .then()
对承诺的调用时遇到问题.执行以下代码时:
I'm having trouble with chaining .then()
calls for a promise. When executing the following code:
var prom = new Promise(function(resolve, reject) {
//let's always fail
reject(Error("buuuu!"));
});
var thenable =
prom.then(
function(done) {
console.log("First handler: Done!: Argument: ", done);
return "First then: DONE";
},
function(fail) {
console.error("First handler: Fail!. Argument: ", fail);
return "First then: FAIL";
}
).then(
function(done) {
console.info("Second handler: Done!. Argument: ", done);
},
function(fail) {
console.error("Second handler: Fail!. Argument: ", fail);
}
);
这将在控制台中打印以下内容:
This prints the following in the console:
First handler: Fail!. Argument: Error {stack: (...), message: "buuuu!"}
Second handler: Done!. Argument: First then: FAIL
为什么第二个 then()
调用了它的 done
处理程序而不是 fail
一个?
Why does the second then()
has its done
handler called instead of the fail
one?
这是 Chrome 的错误吗?(请注意,我只对 Chrome 浏览器的行为感兴趣)
Is this a bug with Chrome? (Note that I'm only interested in Google Chrome's behavior)
我是否需要从 .then
处理程序返回预先解析/拒绝的承诺?
Do I need to resort to returning pre-resolved/rejected Promises from the .then
handlers?
推荐答案
因为您已经在链的第一个 then()
中处理了错误,所以使用您从返回的 "First then: FAIL"
字符串解析承诺
Because you handled the error in the first then()
of the chain already, making the promise resolve with the "First then: FAIL"
string that you returned from it.
这是 Chrome 的错误吗?
不,这就是 Promise 的工作方式.
No, that's how promises are supposed to work.
我是否需要从 .then 处理程序返回预先解析/拒绝的承诺?
你可以这样做,是的.触发第二个失败处理程序的其他方法是:
You can do that, yes. Other ways to trigger the second fail handler would be:
只需省略第一个错误处理程序:
Simply omit the first error handler:
prom.then(function(done) {
console.log("First handler: Done!: Argument: ", done);
return "First then: DONE";
}).then(function(done) {
console.info("Second handler: Done!. Argument: ", done);
}, function(fail) {
console.error("Second handler: Fail!. Argument: ", fail);
});
或者重新抛出异常(类似于返回被拒绝的承诺):
Or rethrow an exception (that's similar to returning a rejected promise):
prom.then(function(done) {
console.log("First handler: Done!: Argument: ", done);
return "First then: DONE";
}, function(fail) {
console.error("First handler: Fail!. Argument: ", fail);
throw new Error("First then: FAIL"); // or: throw fail;
// alternatively, you can return a rejected promise:
return Promise.reject(new Error("First then: FAIL"));
}).then(function(done) {
console.info("Second handler: Done!. Argument: ", done);
}, function(fail) {
console.error("Second handler: Fail!. Argument: ", fail);
});
这篇关于Promise 的第二个 .then() 没有失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!