0

In the following code, the output clearly shows that rejected is within the created promise1 object. Yet when I look at MDN, there is no property indicating whether a promise is resolved or rejected. How does the program know whether a promise is accepted? Where is this information stored?

const promise1 = new Promise((resolve, reject) => {
  throw 'Uh-oh!';
});

console.log(promise1); //Promise { <rejected> 'Uh-oh!' }

promise1.catch((error) => {
  console.error(error);
});
  • 3
    It's internal to the promise object. You cannot see it externally (the console exposes it but there is no defined API for that) – VLAZ Mar 27 '22 at 18:04

2 Answers2

0

There is no public API to check the Promise state, so there is no property that you could check.

Given the impossibility, you can try to do it on your own with any of these solutions:

https://ourcodeworld.com/articles/read/317/how-to-check-if-a-javascript-promise-has-been-fulfilled-rejected-or-resolved

https://github.com/nodejs/node/issues/40054#issuecomment-917641057

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

If I correctly get the question, you ask about the cases upon which JS itself rejects the promise. A promise is rejected when an error is returned from the callback function. In general case you (the programmer) define the conditions which mean success or error according to the code business. Based on what you need, you can either throw or reject the promise and this Q&A looks helpful. But when a promise is gonna be used with a specific purpose, this behavior seems more clear, say when you use JS fetch api, there are solid situations in which the promise would be rejected.i.e. network disconnections or CORS errors. Here you can find a more detailed reply. These situations are those which are not biased towards any data transfer protocol such as HTTP. Finally, here, you can find a pretty well explained pattern for designing your promise workflow.

BaN
  • 105
  • 9