Reputation:
Below is the promise chaining code:
new Promise(function(resolve, reject) {
console.log('first');
resolve('yes');
}).then(
new Promise(function(resolve, reject) {
console.log('second');
reject('no');
})
).catch(rej => console.log(rej));
And the output is :
'first'
'second'
I expected to get a 'no' output, but there wasn't. I don't know why the catch didn't catch the rejection from the second .then()?
Upvotes: 1
Views: 83
Reputation: 370679
.then
only accepts a function as a parameter - your
then(new Promise
is passing the second .then
a Promise (that gets initialized *when the Promise
chain is created, not when the prior Promise
resolves). But .then
doesn't know what to do when it's passed a Promise
, it only deals with function parameters.
Instead, pass .then
a function, and have that function create the Promise to be returned, and it will be properly caught:
new Promise(function(resolve, reject) {
console.log('first');
resolve('yes');
}).then(
() => new Promise(function(resolve, reject) {
//^^^^^^
console.log('second');
reject('no');
})
).catch(rej => console.log('catch: ' + rej));
Upvotes: 4