ES6 Promise
Promise
Promise, like Generator from the previous chapter, is also a solution for asynchronous programming.
You can find similar approaches for handling async operations in jQuery and Angular.
Basic Usage
// First, instantiate a Promise
var promise = new Promise(function(resolve, reject) {
// Promise has two parameters: resolve and reject — one for success, one for failure
if (/* true or false */){
resolve(value); // Success: executes the first callback of promise.then
} else {
reject(error); // Failure: executes the second callback of promise.then
}
});
promise.then(function(value){
// When resolve() runs in the Promise function, this executes
// It receives the parameter passed to resolve
},function(error){
// When reject() runs in the Promise function, this executes
// It receives the parameter passed to reject
}).catch(function(error){
// If either callback in then throws an error, catch handles it
// This prevents the code from stopping execution due to errors
})
That’s a complete Promise usage example. Simple, isn’t it?