admin管理员组文章数量:1410730
I want the third "then" to not be executed when the second "then" is called. However, it still calls the third "then" even though the promise is rejected (the second "then" is called) and the code returns "rejected" and then "undefined". How to not run the third "then" so the "undefined" won't show up?
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);
})
I want the third "then" to not be executed when the second "then" is called. However, it still calls the third "then" even though the promise is rejected (the second "then" is called) and the code returns "rejected" and then "undefined". How to not run the third "then" so the "undefined" won't show up?
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);
})
Share
Improve this question
edited Dec 11, 2017 at 14:44
Damon
4,3562 gold badges18 silver badges27 bronze badges
asked Dec 11, 2017 at 14:39
januaryanandajanuaryananda
4071 gold badge6 silver badges16 bronze badges
1 Answer
Reset to default 9That's because you caught the error in the catch
statement - i.e. .then(null,errorcallback)
- and you never threw another error or returned a rejected promise in it.
...which is the same as returning a resolved promise with a value of undefined, which is why your next .then
executes the success callback.
If you want your error to propagate to a subsequent .catch
or .then(null,fn)
, then your errorcallback
must throw (or return a rejected promise):
function errorcallback(msg) {
console.log(msg);
throw new Error(msg); //or (return Promise.reject(msg);
}
Keep in mind that in every .catch
(or .then(null,fn)
you have to re-throw (or return a rejected promise) in order for subsequent error callbacks to get called.
本文标签: Javascript promise quotthenquot always runs even though the promise failed to executeStack Overflow
版权声明:本文标题:Javascript promise "then" always runs even though the promise failed to execute - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744301682a2599612.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论