Reputation: 1396
I am having some trouble understanding Javascript promises, specifically chaining them and passing errors up the chain. In the following code:
function myPromise() {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log('done')
reject('resolved');
}, 1000);
});
}
function myOtherPromise() {
return new Promise((resolve, reject) => {
myPromise().then(done => {
resolve(done);
}).catch(e => {
console.log('In myOtherPromise, caught err: ', e);
reject(e)
});
});
}
myOtherPromise().then(done => {
console.log('done calling myOtherPromise: ', done);
}).catch(e => {
console.log('caught err from myOtherPromise', err);
});
The output shows:
done
In myOtherPromise, caught err: resolved
I don't understand why the following is not printed:
'caught err from myOtherPromise'
I feel like there is something fundamental I am not quite getting. Why doesn't the rejection from myOtherPromise
get passed to the final catch
block?
Upvotes: 0
Views: 65
Reputation: 5439
You catch the error into the e
variable, but output the err
variable (which is undefined and causes runtime error).
.catch(e => {
console.log('caught err from myOtherPromise', err);
})
Should be:
.catch(e => {
console.log('caught err from myOtherPromise', e);
})
Upvotes: 4