简体   繁体   中英

(Javascript) why the catch doesn't catch the rejection?

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()?

.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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM