9

Here is the code in question:

new Promise((resolve, reject) => {
  const opts = {
    credentials: 'same-origin',
  };

  fetch(`/_api/myAPI`, opts)
  .then((res) => {
    if (!res.ok) {
      reject(res);
    } else {
      ...

If the url throws an exception a 401, when the execution reaches reject(res); it throws Uncaught (in promise)

Even after I add a .catch after the .then call, i.e.

  fetch(`/_api/myAPI`, opts)
  .then((res) => {
    if (!res.ok) {
      reject(res);
    } else {
      ...
   })
  .catch((e) => {
    console.log(e);
   }

it still happens.

Why reject will throw this exception and how can I fix it? My experience is limited to jQuery.Promise and I don't a reject within a failure handler will trigger this error.

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • 3
    Wrapping fetch promise into a new promise is [an antipattern](http://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it). And it causes ill effects here. – Estus Flask Apr 23 '16 at 13:19
  • @estus Thanks for the informative comment! – Anthony Kong Apr 24 '16 at 01:56

1 Answers1

10

When you're rejecting the promise, you're immediately rejecting the promise that is wrapping that entire operation, so you would never get to that catch block.

An analogy: reject and resolve are to promises as return is to functions.

I think what you are trying to do is the code below.

new Promise((resolve, reject) => {
  const opts = {
    credentials: 'same-origin',
  };
  fetch(`/_api/myAPI`, opts)
  .then((res) => {
    if (!res.ok) {
      return Promise.reject()
    } else {
      ...
      resolve(...);
   })
  .catch((e) => {
    console.log(e);
    reject();
   }
}
gnicholas
  • 2,041
  • 1
  • 21
  • 32
  • 1
    I know this thread is stale but is it possible that, at least in Chrome, it *always* displays that error when rejecting a promise? I think that's what I'm seeing. I tried it with a do nothing promise that immediately rejects and still got the error. Does anybody else see this behavior? – John Carrell Mar 17 '17 at 20:32
  • I believe you are correct as well. my code reaches the catch, and i've tried both throwing an error and just promise.reject(). both display this in chrome for me. – Kelly Milligan Apr 07 '17 at 17:21