So Jeremy answers what happens:
const p = Promise.reject(Promise.resolve(3));
p is a rejected promise with a negative value of a Promise of 3.
We have been taught to believe that promises will never be resolved with promises! Well, this is a special case. Here we reject the promise with another promise contrary to what then does.
But why?!?
Easy to sport there. Let me first omit some terminology.
The promised beginning as expected , it can either become:
- done - mark completed with value.
- rejected - flagging failed for a reason.
So far so good, but consider two additional terms:
- allowed - this means that he has decided a different meaning of the promise and is tracking it.
- sett - this means that it is truly fulfilled or rejected - either through a promise that it has resolved, or by itself.
Phew Now this one:
What Promise.resolve does creates a promise resolved to a different value. If this value is the promise that it keeps track of, then otherwise it is immediately set with the value passed. This also happens if you return from inside then or await something in the async function.
What Promise.reject does creates a promise rejected by another value. He has no chance to follow another promise, because it is immediately created with a rejected result.
This behavior is specified in reject and resolve . In particular, we create the promise opportunity and resolve is special - namely, take a look at the "Promise Resolution Functions".
Well, you told me what was going on, but why?!?!?!?
Ok, consider alternatives. We want resolve simulate a return from then or expect in the async function and reject to simulate throw ing in then or in the async function.
const p = Promise.resolve().then(() => { throw Promise.reject(5); });
Clearly, resolving p to 5 does not make sense! We noted that the promise was fulfilled correctly, but it clearly did not end correctly.
Similarly:
asynchronous function foo () {quit Promise.resolve (5); } Foo (); // no one expected a solution to foo .
How about a deviation with an expanded value?
This would mean that we are losing information about what kind of denial we are dealing with. The only alternative is to reject using the Promise object.
Should I ever run into this?
No never. You should never throw promises anyway, and you should always reject using Error s .