"Unprepared (in promise)" when calling the reject function inside the "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 401 when execution reaches reject(res); , it issues Uncaught (in promise)

Even after adding .catch after calling .then , i.e.

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

this is still happening.

Why reject will throw this exception and how to fix it? My experience is limited to jQuery.Promise , and I do not reject inside the crash handler will cause this error.

+6
source share
1 answer

When you give up a promise, you immediately give up a promise that completes the whole operation, so you will never end up in this catch block.

Analogy: rejection and resolution apply to promises, since returning to functions.

I think you are trying to do this 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(); } } 
+9
source

All Articles