I have an issue with promise in 'Angular 2'.
Please see my code below:
getPromise1().then((result) => {
console.log("promise1 result");
}, (error) => {
console.log("promise1 error");
});
function getPromise1() {
return getPromise2().then((result) => {
console.log("promise2 result");
}, (error) => {
console.log("promise2 error");
});
}
function getPromise2() {
return new Promise((resolve, reject) => {
reject("error");
});
}
And the result is: promise2 error
and promise1 result
.
I don't know why not promise2 error
and promise1 error
Any problem and the solution for this case?
This is preview link: http://plnkr.co/edit/RTc1wYfO8e1YPUrXM6GN
When a promise rejects, the control jumps to the closest rejection handler down the chain.
so, Here the .catch
block finishes normally. So the next successful handler is called. Or it could return something, that would be the same.
Hence the result
And the result is:
promise2 error
andpromise1 result
.
So you could have as many .then as we want, and then use a single .catch at the end to handle errors in all of them.
But to get the following result
I don't know why not
promise2 error
andpromise1 error
you need to re-throw the error
throw error;
And here the .catch block analyzes the error and throws it again:
function getPromise1() {
return getPromise2().then((result) => {
console.log("promise2 result");
}, (error) => {
console.log("promise2 error");
throw error;
});
}