Monday, November 11, 2019

javascript - Why is `.catch` callback not triggered



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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...