A promise is in one of three states: pending, fulfilled, or rejected. A promise has two 'fates': resolved or unresolved. A promise is settled if it's either fulfilled or rejected.
Promises are chained with .catch
, .then
, and .finally
.
Each of these return its own promise, which can then subsequently be chained.
.then
does accept two arguments, onFulfilled
and onRejected
. It's called when a promise is resolved.
If an error is returned, the promise will be a rejected promise - otherwise it will be a resolved promise.
prom1.then(console.log).catch(console.log); /* very similar to prom1.then(console.log, console.log); */
A .catch
is essentially a .then
, without the onFulfilled
argument. It's called when a promise is rejected
.catch
should always be used somewhere in the chain to handle errors. As this also returns a promise, it's possible to .then
a .catch
block. If you want to skip from one .catch
to another, avoiding any .then
s in between, you can re-throw an error.
Not having any .catch
chain will mean you have to deal with Unhandled promise rejection
errors.
.finally
will always run once the promise is settled, regardless of it being fulfilled or rejected. This is handy for cleanup and other tasks which you want to always run.
Promise.resolve
and Promise.reject
both exist to return a resolved and rejected promise with a value, respectively.
The next link in the chain will receive the return value of the previous, as they each are returning their own promise with data inside. If you want to pass data from one .then
to another, make sure to return
the value explicitly, not just use it.
It's generally better to use a .then
with a .catch
to handle resolved and rejected promises respectively, as it's easier to parse. It also allows you to have one area to catch all errors, including errors that may happen in the resolve function.
When using a .then
only, if the onFulfilled
function errors, it won't be caught by the onRejected
in the same .then
.
https://www.joshwcomeau.com/javascript/promises/
[[20210224175602-promises-states-fates]]