Anthony Kong Anthony Kong - 7 months ago 41
Javascript Question

" Uncaught (in promise) " when calling the reject function inside a fetch 'then' method

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.

Answer

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();
   }
}