0

I have a function which takes a function that returns a Promise and I am calling it like so:

const test = (prom) => {
  prom()
  .then(() => console.log('top level then'))
  .catch(() => console.log('top level catch'));
};
test(() => new Promise(() => fetch()
  .then(() => console.log('inner level then'))
));

The fetch() call will return an error because I'm not actually fetching anything but the top level catch is not running - why is that?

The behaviour I'm looking for is that everytime the prom Promise resolves, the top level then will run and everytime it rejects, the top level catch will run (in addition to any inner level then and catches).

Ogen
  • 6,499
  • 7
  • 58
  • 124
  • `fetch()` already returns a promise so there's no need to wrap it in another one. This is a classic example of the [explicit promise construction anti-pattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – Phil Sep 26 '18 at 01:22
  • I'd even go so far as to see this is a duplicate. Not so much the question but in applying the answers (by unwrapping the `fetch()` promise), your problem will be solved – Phil Sep 26 '18 at 01:27

1 Answers1

0

It is because your new promise doesn't resolve or reject anything.

test(() => new Promise((resolve, reject) => fetch()
  .then(() => {
    console.log('inner level then');
    resolve();
  })
  .catch(() => {
    console.log('inner level catch');
    reject();
  })
));
Prasanna
  • 4,125
  • 18
  • 41
  • 1
    This is an anti-pattern. There's no reason to wrap `fetch()` in a new promise. Just `return fetch().then()`. No need to make a new promise. – jfriend00 Sep 26 '18 at 04:42