JavaScript Promises - What You Need To Know
The four functions you need to know
1.
The two functions you should know
new Promise(fn)
Promise.resolve(value)
fntakes two arguments: resolveand reject
resolveand rejectare both functions which can be called with one argument
Returned promise will be rejected if an exception is thrown in the passed in function
2.
promise.then(onResolve, onReject)
value
valueis a promise, just returns value
Returns a promise which resolves to
If
Promise.reject(value)
value
promise.catch
Returns a rejected promise with the value
Returns a promise
Useful while processing errors with
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
Use `Promise.reject` to return a rejected promise from
Make sure to follow by
3.
onReject
promise.catch
Patterns
Promisify a callback-accepting function
promise.catch(onReject)
fn
fntakes two arguments: callback(error, data),
erroris nullif successful, and datais null if unsuccessful.
Assume callback passed to
Returns a promise
Equivalent to
4.
promise.then(null, onReject)
Promise.all([promise1, promise2, ...])
Returns a promise
When all arguments resolve, returned promise resolves to an array of all results
When any arguments are rejected, returned promise is immediately rejected with the
same value
Useful for managing doing multiple things concurrently
Packages
where
new Promise(function(resolve, reject) {
fn(function(error, data) {
if (error) {
reject(error);
}
else {
resolve(data);
}
});
});
es6-promise - Polyfill older browsers
bluebird - Get extra promise methods
promisify-node - Promisify callback-accepting functions (npm)
Extra Reading
Are JavaScript Promises swallowing your errors?
Promises at MDN
Promise browser support at Can I Use
Catch exceptions thrown in `then` handlers
promise
.then(function() { ... })
.catch(function(err) {
console.log(err.stack);
});