Vous êtes sur la page 1sur 1

JavaScript Promises - What You Need To Know

The four functions you need to know The two functions you should know

1. new Promise(fn) Promise.resolve(value)


fntakes two arguments: resolveand reject Returns a promise which resolves to value
resolveand rejectare both functions which can be called with one argument If valueis a promise, just returns value
Returned promise will be rejected if an exception is thrown in the passed in function
Promise.reject(value)
2. promise.then(onResolve, onReject)
Returns a rejected promise with the value value
Returns a promise Useful while processing errors with promise.catch
Returned promise resolves to value returned from handler

Chain by returning a promise from onResolveor onReject


Returned promise will be rejected if an exception is thrown in a handler
Patterns
Use `Promise.reject` to return a rejected promise from onReject
Make sure to follow by promise.catch Promisify a callback-accepting function fn
3. promise.catch(onReject)
Assume callback passed tofntakes two arguments: callback(error, data),
Returns a promise
where erroris nullif successful, and datais null if unsuccessful.
Equivalent to promise.then(null, onReject)
4. Promise.all([promise1, promise2, ...]) new Promise(function(resolve, reject) {
Returns a promise
fn(function(error, data) {
When all arguments resolve, returned promise resolves to an array of all results
if (error) {
When any arguments are rejected, returned promise is immediately rejected with the
reject(error);
same value
}
Useful for managing doing multiple things concurrently else {
resolve(data);
}
});
Packages });
es6-promise - Polyfill older browsers

bluebird - Get extra promise methods

promisify-node - Promisify callback-accepting functions (npm)


Catch exceptions thrown in `then` handlers

promise
Extra Reading
.then(function() { ... })
Are JavaScript Promises swallowing your errors?
.catch(function(err) {
Promises at MDN
console.log(err.stack);
Promise browser support at Can I Use
});

Vous aimerez peut-être aussi