-
Notifications
You must be signed in to change notification settings - Fork 86
Promises
tim-hr edited this page Nov 3, 2016
·
1 revision
- Officially introduced into Javascript with ES6
- Available in popular libraries such as Bluebird
- From Mozilla Developer Network: "The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future."
- Takes an ‘executor’ callback function
- Executor callback is executed immediately with resolve and reject functions passed in to be executed on some deferred asynchronous action
- Promises have a ‘then’ method to define what to do when the promise is resolved, and a ‘catch’ method to deal with reject cases
- To create a promise:
- use new Promise constructor
- pass in callback that takes resolve and reject as arguments
- execute some asynchronous function whose callback passes errors to the ‘reject' callback or passes the result to ‘resolve'
-
All
then
andcatch
both return new promises, which allows chaining -
The first
then
call will receive the argument passed intoresolve
. Subsequentthen
calls will receive the return value from the previousthen
orcatch
that was executed. -
Calling
reject
from within the promise will skip to the firstcatch
method. However, any subsequentthen
calls will be executed. -
catch
methods are executed in 2 situations: (1) whenreject
is called inside the promise or (2) an error isthrow
n from within a promise orthen
/catch
method. -
If a promise is
reject
ed, only the first instance of thecatch
method will be called. Subsequent catches will only execute if additional errors are thrown.
-
Promise.all
can be used to wait for multiple promises to resolve before executing thethen
method. Thethen
method will be passed an array of resolved values from the promises. For example, in the below code, the[1, 2, 3]
will be logged to the console after all three promises have resolved. - If any promise in the
Promise.all
calls the reject function, thenPromise.all
will execute thecatch
method instead of thethen
method.
let array = [];
let a = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 200)
})
let b = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 500)
})
let c = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 100)
})
Promise.all([a, b, c])
.then((values) => {
console.log(values); // [1, 2, 3]
});
- Promises can be chained via their ‘then’ and ‘catch’ methods