3

Usually the two Promise objects are created across function calls. I have put the promises together showing what I would expect to happen:

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 should have propagated the reject into my parent promise. How can I capture the rejectCall_2 in the outer promise?

jcalfee314
  • 4,642
  • 8
  • 43
  • 75
  • Why do you need to nest 2 promises? I can't see any use case that would lead to this kind of code. – Florian Margaine Jul 09 '15 at 15:57
  • 1
    Side-comment: reject errors, not strings. i.e. `reject(new Error('rejectCall_2'));` – Florian Margaine Jul 09 '15 at 15:58
  • Why are you wrapping a promise-returning method call in a promise constructor? If you have `foo.bar()` that returns a promise, you can simply `foo.bar().catch(e => ...)`. – ssube Jul 09 '15 at 16:03
  • We have various actions that return a promise, which often call into the indexed db database layer which also return promises. I don't see how you would hard-code promise sharing, we just let everything return a promise then chain them together. – jcalfee314 Jul 09 '15 at 16:38
  • 1
    This looks a *lot* like the [promise construction antipattern](http://stackoverflow.com/q/23803743/1048572). You should just chain things together without using `new Promise`. – Bergi Jul 09 '15 at 19:51

1 Answers1

2

You don't return anything from inside new Promise. Whatever you return is just thrown away, What you do is resolve and reject. If you want to "return" something, including another promise, what you do is resolve with that something.

So what you want is

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 might as well use the immediate return fat-arrow format and save yourself a few curly braces:

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

I would take note of the comments which suggest you may be guilty of the "explicit promise constructor anti-pattern', where you construct a promise only to resolve or reject it with some other promise that you could have just used in the first place. I'm assuming your example is an artificial one designed to showcase your particular issue.