0

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?

iamthegreenfairy
  • 1,316
  • 1
  • 10
  • 9
  • 2
    because that function throws an error when trying to call console.log() `ReferenceError: err is not defined` ;) – Thomas Jun 11 '16 at 16:46
  • Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Jun 11 '16 at 17:07

1 Answers1

4

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);
})
Ruslan Stelmachenko
  • 4,987
  • 2
  • 36
  • 51