I have the following code that uses native promises:
function getUser() {
return new Promise(function (resolve, reject) {
reject();
});
}
function changeUser() {
return new Promise(function (resolve, reject) {
return getUser().catch(function (responseData, test) {
console.log('boo error'); // this logs `boo error`
throw {};
});
});
}
changeUser().then(function () {
console.log('done');
}).catch(function () {
console.log('error'); // this is not triggered
});
When I run it, the lst catch block with console.log('error'); is not executed. Why is that? Is the implementation of native promises different from Q?
Answer
Because you never reject the promise you return from changeUser. You're only throwing within the chain of the promise returned from getUser, which cascades within that chain, but doesn't influence the new Promise constructed in changeUser.
Either:
return new Promise(function (resolve, reject) {
return getUser().then(resolve, function (responseData, test) {
console.log('boo error'); // this logs `boo error`
reject();
});
});
Or:
function changeUser() {
return getUser().catch(function (responseData, test) {
console.log('boo error'); // this logs `boo error`
throw {};
});
}
No comments:
Post a Comment