-
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
thenandcatchboth return new promises, which allows chaining -
The first
thencall will receive the argument passed intoresolve. Subsequentthencalls will receive the return value from the previousthenorcatchthat was executed. -
Calling
rejectfrom within the promise will skip to the firstcatchmethod. However, any subsequentthencalls will be executed. -
catchmethods are executed in 2 situations: (1) whenrejectis called inside the promise or (2) an error isthrown from within a promise orthen/catchmethod. -
If a promise is
rejected, only the first instance of thecatchmethod will be called. Subsequent catches will only execute if additional errors are thrown.
-
Promise.allcan be used to wait for multiple promises to resolve before executing thethenmethod. Thethenmethod 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.allcalls the reject function, thenPromise.allwill execute thecatchmethod instead of thethenmethod.
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