How to propagate deviation in ES6 promise chain?

Typically, two Promises are created through function calls. I put promises together so that I would expect to see:

new Promise((resolve, reject) => {

    //function call with returned promise...

    return new Promise((resolve, reject) => {

      reject("rejectCall_2")  //Prints nothing

    })

}).catch( e1 => {
  console.log('e1',e1) 
})

      

This was to extend the rejection to my parenting promise. How can I capture rejectCall_2 in the outer promise?

+3


source to share


1 answer


You don't return anything from the inside new Promise

. Whatever you return is just thrown away, what you do is decision and rejection. If you want to "return" something, including another promise, what you do is okay with that.

So you want

new Promise((resolve, reject) => {
    //function call with returned promise...
    resolve(new Promise((resolve, reject) => {
    ^^^^^^^
      reject("rejectCall_2")
    }));
}).catch(e1 => {
  console.log('e1', e1) 
})

      

Tested with babel-node.



FWIW, you can also use the immediate fat arrow format and keep multiple curly braces:

new Promise((resolve, reject) => 
    resolve(new Promise((resolve, reject) => 
      reject("rejectCall_2")
    ));
).catch( e1 => console.log('e1',e1));

      

I would like to take note of the comments that suggest that you might be guilty of the "explicit promise constructor concept" where you build a promise only to resolve or reject it with other promises that you could only use in the first place. I am assuming your example is artificial, intended to demonstrate your specific problem.

+2


source







All Articles