What is a Promise ?
A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved. A promise may be in one of the 3 possible states: fulfilled, rejected or pending. Promise user can attach callbacks to handle the fulfilled value or the reason for rejection.
then
The first argument of .then
is a function that runs when the promise is resolved and
receives the result. The second argument of .then
is a function that runs when
the promise is rejected and receives the error.
Chaining
Value returned by then
is used in next then
by calling with that value.
However if a promise is returned, the next then
waits on it and is only
called when the promise settles.
catch
The catch
callback is executed when the promise is rejected.
catch
is just a syntactic sugar for then(undefined, func)
, but it’s more
readable.
finally
finally
callback is called regardless of success or failure
Its a good handler for performing cleanup.
Static Methods
- Promise.resolve() - Creates a promise that resolves to value given to it.
- Promise.reject() - Create a promise that rejects with the value given to it.
- Promise.all(array) - Make a promise that fulfills when every itme in the array fulfills and rejects if any item rejects.
- Promise.race() - Make a promise that fulfills as soon as any item fulfills or rejects as soon as any item rejects.
Promise States
- Fulfilled - The action relating to the promise suceeded.
- Rejected - The action relating to the promise failed.
- Pending- Hasn’t fulfilled or rejected yet.
- Settled - Has fulfilled or rejected.