jan*_*nda 4 javascript promise deferred
我希望在调用第二个“then”时不执行第三个“then”。然而,即使承诺被拒绝(第二个“then”被调用)并且代码返回“rejected”然后“undefined”,它仍然调用第三个“then”。如何不运行第三个“then”,这样“undefined”就不会出现?
var FirstPromise = function() {
let promiseme = new Promise(function(res, rej) {
if ('a' == 'b') {
res(1);
} else {
rej('rejected');
}
})
return promiseme;
};
function succeddcallback(msg) {
return msg * 2;
}
function errorcallback(msg) {
console.log(msg);
}
FirstPromise()
.then(succeddcallback, null)
.then(null, errorcallback)
.then(function(succedded) {
console.log(succedded);
}, function(failed) {
console.log(failed);
})
Run Code Online (Sandbox Code Playgroud)
那是因为你在catch语句中发现了错误——即.then(null,errorcallback)——并且你从未在其中抛出另一个错误或返回一个被拒绝的承诺。
...这与返回值为 undefined 的已解决承诺相同,这就是您 next.then执行成功回调的原因。
如果您希望您的错误传播到后续的.catchor .then(null,fn),那么您errorcallback必须抛出(或返回一个被拒绝的承诺):
function errorcallback(msg) {
console.log(msg);
throw new Error(msg); //or (return Promise.reject(msg);
}
Run Code Online (Sandbox Code Playgroud)
请记住,在每个.catch(或者.then(null,fn)您必须重新抛出(或返回被拒绝的承诺)以便调用后续错误回调。
| 归档时间: |
|
| 查看次数: |
1956 次 |
| 最近记录: |