Back to: JavaScript Tutorial For Beginners and Professionals
JavaScript Promise with Examples
In this article, I am going to discuss the JavaScript Promise with Examples. At the end of this article, you will understand the following pointers in detail.
- Why JavaScript Promise?
- What is Promise?
- A real-life example of Promise
- Where to use Promises
- The JavaScript Promises States and Control flow
- Understanding then(), catch(), and finally() methods of promise object
- Why we use Promise in JavaScript?
Why JavaScript Promise?
JavaScript is single-threaded long-running operations that block other operations. In JavaScript code is executed synchronously that is in sequential order that we saw in the previous article of callback one. Synchronous means the code is executed one by one like one line is executed then the next line is executed and so on. This means each statement has to wait for the previous statement to finish executing. Long-running JavaScript functions can make the UI or server unresponsive until the function has returned. This can make a terrible user-experience.
Asynchronous operation in JavaScript breakup long operation into shorter ones so other operations can execute. Asynchronous delayed execution by postponing the heavy operation to the end of the event loop, to give event handlers the ability to respond.
Asynchronous code takes statements outside of the main program flow, allowing the code to run without blocking and waiting for the result or other to finish. Anything that needs to wait for the promise to proceed, we need to put this in.then().
What is Promise?
In JavaScript promise is the same as a promise we make in real life. When we make a promise in real life, it is assured that we are going to do keep in the future. As promises can only be made for the future.
A promise has 2 general outputs: it will either be kept when the time comes, or it won’t. This is the same for promises in JavaScript. When we declare a promise in JavaScript, it will be resolved when the time comes, or it will get rejected.
Real-life example:
Suppose you are appearing for the exam; your dad promises you to give the new mobile after getting a pass with first class. That is Promise, A promise has 3 stated
- Pending: You don’t know if you will get the mobile
- Fulfilled: Dad is happy with your first class and he will give you the new mobile
- Rejected: Dad is not happy as you didn’t get the first class, he withholds the new mobile.
JavaScript Promises
In JavaScript, a Promise is used for performing asynchronous operations. It represents a result that may be available now, or in the future or never. Promises are easy to manage when dealing with multiple asynchronous operations.
Where to use Promises
When we are using API and want to make an asynchronous call to remote web services and requesting some data from web service then the JavaScript promise promises us to get data from web services and we can use it in the future. It is used for handling asynchronous events and It’s mostly used for handling the asynchronous HTTP requests
Promises features
- It’s good for handling asynchronous operation
- Good for handling multiple asynchronous operations
- Provide better error handling
- It improves the code readability
The JavaScript Promises States and Control flow
A promise has three states:
- Pending: A promise starts in the pending state which says that the promise has not yet completed and ends in either fulfilled(success) state or rejected(fail) state.
- Fulfilled: The operation has finished, and the promise is fulfilled with a value.
- Rejected: An error has occurred during the operation, and the promise is rejected with an error.
Note: A promise starts in the pending state and ends in either a fulfilled state or a rejected state.
JavaScript Promise Control flow
A promise is said to be settled or resolved when it is either fulfilled or rejected. Once a promise is settled, it becomes immutable, and its state cannot change. The then() and catch() methods of a promise can be used to attach callbacks that execute when it is settled. These callbacks are called with the fulfillment value and rejection reason, respectively.
The Constructor syntax for a promise object: let promise=new Promise((resolve, reject) => { … })
Firstly, we use a promise constructor i.e. new Promise() to create a promise object. The Promise constructor accepts a function as a parameter. This function is called the executor. new Promise the executor accept two functions with names resolve() and reject().
When we call a new Promise(executor), the executor is called automatically. According to the condition, inside of executor we manually call the resolve () function if condition met then the promised is completed successfully and call the reject () function if the condition didn’t meet then promise is rejected in case of an error occurs.
Example:
<html> <head> <title>JavaScript Promise example</title> </head> <body> <script> let passexam = true; let res = new Promise(function (resolve, reject) { if (passexam) { resolve("Dad gifted the new mobile."); } else { reject("Dad has not gifted the mobile."); } }); </script> </body> </html>
We learned that promise starts in a pending state. To see the pending state of the promise we wrap the code of new Promise(executor) in the setTimeout() callback function.
Example:
<html> <head> <title>JavaScript Promise with setTimeout() function example1</title> </head> <body> <script> let passexam = true; let res = new Promise(function (resolve, reject) { setTimeout(() => { if (passexam) { resolve("Dad gifted the new mobile."); } else { reject("Dad has not gifted the mobile."); } }, 5 * 1000); }); console.log(res); </script> </body> </html>
Now we see that the promise starts with a pending state with the value is undefined. The promised value will be returned after once the promise is fulfilled/completed.
Output:
After 5 seconds the timer finish, the variable res is get logged in using console.log() in the console window, we can see that the promise state is now become resolved and the value is what we passed to the resolve() function
On calling the resolve() function move the promise object from pending to fulfilled stated. If we change the value of passexam variable to false and execute the program
Example:
<html> <head> <title>JavaScript Promise with setTimeout() function example2</title> </head> <body> <script> let passexam = false; let res = new Promise(function (resolve, reject) { setTimeout(() => { if (passexam) { resolve("Dad gifted the new mobile."); } else { reject("Dad has not gifted the mobile."); } }, 5 * 1000); }); console.log(res); </script> </body> </html>
We notice that this time reject() function is being called and displays the error message after 5 seconds and the state of the promise object becomes rejected after 5 seconds.
Output:
In other words, on calling reject() function moves the promise object to a rejected state. Once the promise reaches either fulfilled state or reject state. it cannot change means It cannot go back from the reject state to fulfilled state and vice versa. It also cannot go back to pending state from a fulfilled state or reject state.
As we saw the Promise control flow section when we create a Promise object using a new Promise, that time the promise is in the pending state that is not resolved nor rejected. To attach callback that executes the promise when it is in either fulfilled or reject state, we can call the Promise object methods then(), catch(), and finally().
Consuming the Promise in JavaScript
We can consume the Promise by calling then(), catch(), and finally() methods of promise object.
The then() method
The then() method is used to attach fulfillment callback to promise when the promise is resolved.
Syntax of then(): promiseObject.then(onFulfilled, onRejected);
The then() method takes two parameters
- The onFullfilled callback is called if the promise is fulfilled.
- The onRejected callback is called if the promise is rejected.
The following example returns a Promise object
<html> <head> <title>JavaScript Promise then() method example</title> </head> <body> <script> function doPromise(passexam) { return new Promise(function (resolve, reject) { setTimeout(() => { if (passexam) { resolve("Dad gifted the new mobile."); } else { reject("Dad has not gifted the mobile."); } }, 5 * 1000); }); } let passexam = doPromise(true); passexam.then( success => console.log(success), err => console.log(err) ); </script> </body> </html>
Output:
In the above example, doPromise(true) call the doPromise function and invoked the then() method.
The catch() method
The catch() method is used to attach rejection callback to promise when the promise is rejected. The function passed as the second parameter to .then() method of a promise object
passexam.catch(
error => console.log(error)
);
Internally, the catch() method invokes the then(undefined, onRejected) method.
Example:
<html> <head> <title>JavaScript Promise catch() method example</title> </head> <body> <script> function doPromise(passexam) { return new Promise(function (resolve, reject) { setTimeout(() => { if (passexam) { resolve("Dad gifted the new mobile."); } else { reject("Dad has not gifted the mobile."); } }, 5 * 1000); }); } let passexam = doPromise(false); passexam.then( success => console.log(success) ); passexam.catch( error => console.log(error) ); </script> </body> </html>
Output:
The above code can also be rewritten like this
<html> <head> <title>JavaScript Promise catch() method using then() example</title> </head> <body> <script> const res = new Promise((resolve, reject) => { const passexam = false; // An asynchronous operation. setTimeout(() => { if (passexam) { resolve("Dad gifted the new mobile."); } else { reject("Dad has not gifted the mobile."); } }, 5 * 1000) }); res.then(result => console.log(result), err => alert(err)); </script> </body> </html>
Output:
The finally() method
The finally() method is the same as try catch finally block we studied in exception chapter where the finally block always executed whether the error has occurred or not. Here the finally() method is also the same. Sometimes, we want to execute the same piece of code whether the promise is fulfilled or rejected.
Example:
<html> <head> <title>JavaScript Promise finally() method example</title> </head> <body> <script> const res = new Promise((resolve, reject) => { const passexam = false; // An asynchronous operation. setTimeout(() => { if (passexam) { resolve("Dad gifted the new mobile."); } else { reject("Dad has not gifted the mobile."); } }, 5 * 1000) }); function finalcall() { console.log("finally is calling...") } res.then(result => console.log(result)) .catch(err => console.log(err)) .finally(() => finalcall()) </script> </body> </html>
Output:
Why we use Promise in JavaScript?
A Promises provide a robust way to wrap the (possibly pending) result of asynchronous work, mitigating the problem of deeply nested callbacks, known as “callback hell”. In other words, before promises, callback function and event were used but they had limited functionalities as we saw in the previous article.
A callback is a function that is to be executed after another function has finished executing , thus the name call back. Multiple callbacks would create callback hell issues that lead to a chunk of unmanageable code i.e.: not manageable. Events were not good at handling asynchronous operations.
So, we can say that Promises are the best choice for handling asynchronous operations also handle multiple asynchronous operations easily and provide better error handling than compare to callbacks and events.
Example: Callback hell
<html> <head> <title>JavaScript callback hell example</title> </head> <body> <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <script> let resultA, resultB, resultC, resultD; function sum(num1, num2, callback) { const cb = $.Callbacks(); cb.add(callback); cb.fire(num1 + num2); }; sum(1, 2, success => { //callback 1 resultA = success; //you get result = 3 sum(resultA, 3, success => { //callback 2 resultB = success; //you get result = 6 sum(resultB, 4, success => { //callback 3 resultC = success; //you get result = 10 sum(resultC, 5, success => { //callback 4 resultD = success; //you get result = 15 console.log('total: ' + resultD); console.log(resultA, resultB, resultC, resultD); }); }); }); }); </script> </body> </html>
Output:
The above code snippet syntax is not so user friendly. In normal terms, it looks like a pyramid and it refers to a Callback hell because the callback nested inside the other callback that is we nested the code four times. We can predict if we have 10 or more callbacks then the code will gonna the next 10 times. So, in order to escape from callback hell, Promise came into rescue.
Look at the Promise version of above same example:
<html> <head> <title>JavaScript callback hell-Promise version example</title> </head> <body> <script> let resultA, resultB, resultC, resultD; function sum(num1, num2) { return Promise.resolve(num1 + num2); }; sum(1, 2) .then(success => { resultA = success; return resultA; }) .then(success => sum(success, 3)) .then(success => { resultB = success; return resultB; }) .then(success => sum(success, 4)) .then(success => { resultC = success; return resultC; }) .then(success => sum(success, 5)) .then(success => { resultD = success; return resultD; }) .then(success => { console.log('total: ' + success) console.log(resultA, resultB, resultC,resultD) }); </script> </body> </html>
Output:
This is the best example of chaining promises. It’s a proper way to inform JavaScript the next thing to do after an asynchronous task is done. The result of the then() method is a Promise.
With promises, we tear down the callback with .then(). In a way, it looks cleaner easier to understand because there is no callback nesting. Of course, with ES7 async syntax, we can even further enhance this example, which we will see in the coming tutorial.
In the next article, I am going to discuss JavaScript Promise Chaining with Examples. Here, in this article, I try to explain the JavaScript Promise with Examples. I hope this JavaScript Promise with Examples article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript Promise with Examples article.
let btn=document.getElementById(‘comment_post_ID’);
btn.addeventListener(‘click’,function(){
window.alert(‘hello world’)
}
let btn=document.getElementById(‘comment_post_ID’);
console.log(btn)
btn.addeventListener(‘click’,function(){
window.alert(‘hello world’)
}