Promise
A promise is an object that may produce a single value some time in the future. The Promise API is a new feature of ECMAScript 6, but it has good browser support already. There are also many libraries which implement the standard Promises API and provide additional methods to ease the use and composition of asynchronous functions
Promises are containers for future values. When the promise receives the value (it is resolved) or when it is cancelled (rejected), it notifies all of its "listeners" who want to access this value.
The advantage over plain callbacks is that they allow you do decouple your code and they are easier to compose.
Status | What is happened |
---|---|
fulfilled | The action relating to the promise succeeded |
rejected | The action relating to the promise failed |
pending | Hasn't fulfilled or rejected yet |
settled | Has fulfilled or rejected |
Constructor
new Promise(function(resolve, reject) {});
resolve(thenable)
Your promise will be fulfilled/rejected with the outcome of thenableresolve(obj)
Your promise is fulfilled with objreject(obj)
Your promise is rejected with obj. For consistency and debugging (e.g., stack traces), obj should be an instanceof Error. Any errors thrown in the constructor callback will be implicitly passed to reject().
method
Method | ||
---|---|---|
Promise.resolve(promise) | ||
Promise.resolve(thenable) | ||
Promise.resolve(obj) | ||
Promise.reject(obj) | ||
Promise.all(array) | ||
Promise.race(array) |
Instance Methods
var processHugeComputation = function processHugeComputation() {
return new Promise(function(resolve, reject){
someComputation(function(data) {
if(data.status === "success"){
resolve(data.payload);
} else {
reject("Error");
}
});
});
}
Promise chain which is called "Thenable"
var promiseObject = processHugeComputation();
promiseObject
.then(function(data){
return data.json();
})
.catch(function(error){
console.error(error)
});
The code is same as below.
promise
.then(resolveCallback, rejectCallback);
Also same as below.
promise
.then(function(){
})
.then(undefined, function(){
});
Major difference is that both function can be called on then
and catch
chain.
// Both function can be called
promise
.then(function(){
})
.catch(function(){
});
// One of these can be called
promise
.then(resolveCB, rejectCB);
Promise#all
Promise.all([arrayofPromises])
.then({
})
.catch({
}) // catch is invoked right after the one of the promise is failed.
https://jakearchibald.com/2014/resolve-not-opposite-of-reject/
https://developers.google.com/web/fundamentals/getting-started/primers/promises
What is the extent of your experience with Promises and/or their polyfills?
What are the pros and cons of using Promises instead of callbacks?
Promise | Callback | |
---|---|---|
Pro | Readability, testablity | Easy to write |
Con | Then callback also still not perfect for readability | Nested callback causes lack of readability |