See the Pen thecodelog.com - ES6 Promises 1 by Deano (@deangilewicz) on CodePen.
The resolve() method handles when the promise is resolved. When there is no value, or any nonpromise value, the promise is fulfilled. If another promise is passed then promise adopts the state (whether immediate or eventual) of the passed promise (either fulfillment or rejection).
See the Pen thecodelog.com - ES6 Promises 2 by Deano (@deangilewicz) on CodePen.
To handle a response from a Promise, the then() method is used, which can take two arguments – a success handler, and an error handler. The arguments to the then() method are optional.
See the Pen thecodelog.com - ES6 Promises 3 by Deano (@deangilewicz) on CodePen.
A more typical way to handle an error is with the catch() method. The catch(failureCallback) is short for then(null, failureCallback).
See the Pen thecodelog.com - ES6 Promises 4 by Deano (@deangilewicz) on CodePen.
Promises can be chained and the catch() method will handle any error in the chain.
See the Pen thecodelog.com - ES6 Promises 5 by Deano (@deangilewicz) on CodePen.
If a new promise is returned, it is available in the next then method. This is true of a rejected promise also. An exception in the first fulfilled() will not result in the first rejected() being called, as that handler only responds to the resolution of the first original promise. Instead, the second promise, which the second then() is called against, receives that rejection.
See the Pen thecodelog.com - ES6 Promises 6 by Deano (@deangilewicz) on CodePen.
Promises can only be resolved (fulfillment or rejection) once. Any further attempts to fulfill or reject are simply ignored. Thus, once a Promise is resolved, it’s an immutable value that cannot be changed.
See the Pen thecodelog.com - ES6 Promises 7 by Deano (@deangilewicz) on CodePen.
In the following example, Promises are used to fetch data from two different sources. The second promise uses returned data from the first promise.
See the Pen thecodelog.com - ES6 Promises 8 by Deano (@deangilewicz) on CodePen.
You can also use Promises to “promisify” non promise code (create a Promise around an old callback API).
See the Pen thecodelog.com - ES6 Promises 9 by Deano (@deangilewicz) on CodePen.
Promise.all() and Promise.race() are two composition tools for running asynchronous operations in parallel.
Promise.all() waits for all fulfillments (or the first rejection).
See the Pen thecodelog.com - ES6 Promises 10 by Deano (@deangilewicz) on CodePen.
Promise.race() waits only for either the first fulfillment or rejection.
See the Pen thecodelog.com - ES6 Promises 11 by Deano (@deangilewicz) on CodePen.