The Promise is an object that may produce a value, sometime in the future, on the completion of an asynchronous operation. The produced value can be either a successful result or an error .
A car factory provides promise to the buyers. It says if the buyers provide the money then they will get a new car in the future.
So here are 2 cases – either the buyers get car (successful result), or if some problem occurs in the factory like workers strike, fire, floods, etc then the money is refunded to the buyers (error).
The syntax is given below:
myPromise = new Promise(function (resolve, reject) {
// some code
});
myPromise.then(
result => { // executes when promise is resolved },
error => { // executes when promise is rejected }
);
The JavaScript will not wait for the promise to finish instead will continue to the next lines of code. When the promise finishes then the consuming functions will automatically be called.
In the below code the promise takes 2 seconds time so JavaScript just continue executing the next lines of code and then after 2 seconds the resolve callback function is called.
Therefore the second console.log will be executed first then afterwards the ‘console.log’ inside the resolve callback function is executed.
myPromise = new Promise(function (resolve, reject) {
setTimeout(resolve, 2000, "completed");
});
myPromise.then(
result => { console.log(result) },
error => { alert(error) }
);
console.log("Doing other work");
Doing other work
completed
1. Implementing TheMovieDB (TMDB) API with jQuery AJAX
2. JQuery AJAX Method to Call an API
3. Implementing Google Contacts API
myPromise = new Promise(function (resolve, reject) {
setTimeout(resolve, 2000, "completed");
});
myPromise.then(
result => { alert(result) },
error => { alert(error) }
);
myPromise = new Promise(function (resolve, reject) {
throw new Error('Something failed');
});
myPromise.then(
result => { alert(result) },
error => { alert(error) }
);
If there happens to be some error then promise gets rejected. You can capture these errors using .catch() method. This method is used after the .then() method.
In the below code I am catching error using the .catch() method. Notice that I haven’t added the error callback function.
myPromise = new Promise(function (resolve, reject) {
throw new Error('Something failed');
});
myPromise.then(
result => { alert(result) }
).catch(result => { alert(result) } );
If there is a need to execute two or more asynchronous operations back to back in such a way that each subsequent operation starts when the previous operation succeeds, also the subsequent operation takes the result of the previous operation. This is accomplished by creating Promise Chaining.
Consider the below code where the result is passed through the chains of ‘.then’ method.
myPromise = new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
});
myPromise.then( // (**)
result => {
console.log(result); // 1
return result * 2;
})
.then(
result => { // (***)
console.log(result); // 2
return result * 2;
})
.then(
result => { // (****)
console.log(result); // 4
});
The output you will get is:
1
2
4
The flow is:
myPromise = new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
});
myPromise.then(
result => {
console.log(result); // 1
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result * 2), 1000);
});
})
.then(
result => {
console.log(result); // 2
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result * 2), 1000);
});
})
.then(
result => {
console.log(result); // 4
});
1
2
4
Here I will call an API that returns random jokes with JavaScript Promise.
The API URL is: https://api.icndb.com/jokes/random.
The JSON returned by it is:
{ "type": "success", "value": { "id": 215, "joke": "Chuck Norris just says no to drugs. If he said yes, it would collapse Colombia's infrastructure.", "categories": [] } }
Run the below code that fetches random joke from the API:
myPromise = new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', 'https://api.icndb.com/jokes/random');
request.onload = () => {
if (request.status === 200) {
resolve(request.response); // we got data here, so resolve the Promise
} else {
reject(request.statusText); // status is not 200 OK, so reject
}
};
request.onerror = () => {
reject(Error('Error fetching data.')); // error occurred, reject the Promise
};
request.send(); // send the request
});
myPromise.then(
result => { console.log(JSON.parse(result).value.joke); },
error => { alert(error); }
);
Explanation: Inside the Promise I am making an XMLHttpRequest object to make an AJAX request. The reason for making AJAX request inside the Promise is because the API will send the response in a few milliseconds time. So promise is a best solution.
When the promise gets the response I am printing the joke in the console.
Download source codes:
DOWNLOAD