A Promise
is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. Promise can either be fulfilled with a value, or rejected with a reason (error). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promises can be attached to callbacks to handle the fulfilled value or the reason for rejection.
The Syntax:
let promise = new Promise(function(resolve, reject) {
// Executor
});
The function passed to new Promise
is called the executor. When new Promise
is created, the executor runs automatically and attempts to perform a job . When it is finished with the attempt, it calls resolve
if it was successful or reject
if there was an error. The arguments resolve
and reject
in the executor are callbacks provided by JavaScript itself. Our code will be only inside the executor.
Consuming Promises:
A Promise object serves as a link between the executor and the consuming functions which will receive the result or error. A promise can be consumed using the .then()
method. The anonymous functions passed as arguments (callbacks) will handle the promise response. You may learn more about callbacks here.
promise.then(
function(response) {
// handle successful response
// This block of code execute only after receiving response
},
function(error) {
// handle error
}
);
Example:
let getPromise = new Promise((resolve, reject) => {
// In this example, we use setTimeout() method to simulate async code.
// In reality, you will be using consuming API.
// Returns "Success!" after a sec
setTimeout( function() {
resolve("Success!");
}, 1000)
})
getPromise.then((response) => {
// response is whatever we passed in the resolve() function above.
console.log("Promise response: " + response);
}, (error){
console.log("Promise Error: " + error);
});
Inclusion of async/await
feature in recent JavaScript edition ES8 has made working working with async functions and promises much more easier. You can learn more about async/await here: What is async/wait in JavaSript