Register Login

Promise in JavaScript

Updated Nov 22, 2022

In JavaScript, the Promise is the fundamental building block for asynchronous operations. Users can use the Promise object to deal with asynchronous operations in JavaScript.

They can easily manage it while handling multiple asynchronous operations as they cannot use callbacks which will create callback hell leading to cumbersome code. But without proper knowledge of JavaScript Promises, users face challenges while working with Promises.

This article brings a detailed discussion on JS Promise, their advantage, and use cases in JavaScript.

What is the Promise in JavaScript?

In JavaScript, the Promise is the ideal and the best way to handle asynchronous operations. They can run multiple asynchronous operations efficiently and accurately.

The JavaScript Promise provides handles errors better than other conventional techniques, callbacks, and events. The Promise object eventually conveys either the completion or failure of an asynchronous process and its consequent value.

In other words, users can also define the JS Promise as the soundest choice for handling multiple callbacks simultaneously. It avoids the undesired callback hell causing an unmanageable code. Promises also provide a more reasonable option for programmers to read their code more virtually and efficiently, especially; if users use the particular code for executing multiple asynchronous operations.

The Promise allows users to relate handlers with all asynchronous operations' eventual success value or failure value with reason. It lets asynchronous operations return values such as synchronous methods instead of directly returning the final output.

The asynchronous operation returns the Promise to pass the value at any time in the future.

States of Promise in JavaScript:

There are three states, and the JavaScript Promise can be in one of these states. These are:

  • The pending state: It is the state where the operation is in the initial state, neither completed nor rejected.
  • The fulfilled state: In this state, the JS Promise completes the operation successfully.
  • The rejected state: This state indicates that it has completed the operation.

Advantages of Promise in JavaScript:

There are several advantages of JavaScript Promise:

  • Using JavaScript Promise can improve the readability of the JS program.
  • The JavaScript Promise can better handle all the asynchronous operations.
  • The JavaScript Promise provides an efficient flow of management definition in asynchronous logic.
  • Promise deals with errors more efficiently than other conventional methods of handling errors.

Users can create a Promise using the Promise constructor. The syntax is as follows:

var Promise = new Promise(function(resolve, reject){
     //do something
});

The parameters of the JavaScript Promise are as follows:

Firstly, the Promise constructor accepts only one argument, i.e., the callback function, and users can refer to that callback function as an anonymous function.

Secondly, the callback function accepts two arguments, namely, resolve and reject

It executes operations inside the callback function, and if it performs the operations successfully, it calls the l resolve parameter. If it does not successfully run the operation, the callback function will call the second parameter, i.e., the reject.

An example of the JavaScript Promise:

Code Snippet:

var Promise = new Promise(function(resolve, reject) {
const a = "Hello JavaScript Promise";
const b = "This is JavaScript Promise"
if(a === b) {
	resolve();
} else {
	reject();
}
});
Promise.
	then(function () {
		console.log('It has successfully executed the operation, Hello JavaScript Promise');
	}).
	catch(function () {
		console.log('Error: An error has occurred');
	});

Output:

Run Code Snippet

Explanation:

We used the Promise object to execute an operation in the above example. We checked whether the two message strings were equal or not using the Strict Equality operator of JavaScript.

If the strings are equal, i.e., the if block executes, the JS Promise will run the first operation of the function "It has successfully executed the operation ....". If the strings are not equal, it will execute the second operation of the function, i.e., it will display the error message "Error: An error has occurred."

There are two Promise Consumers, .then and .catch methods. Let us first discuss the .then method of Promise.

The compiler invokes the .then method when a Promise is resolved or rejected. Users can also define the method as a career that accepts data from the Promise object and further runs the operation successfully.

Syntax:

.then(function(result){
        //handle success
    }, function(error){
        //handle error
    })
This is an example of the Promise resolved:
Code Snippet:

var Promise = new Promise(function(resolve, reject) {
	resolve('Hello JavaScript Promises');
})
Promise
	.then(function(Message1) {
	//it invokes the success handler function
		console.log(Message1);
	}, function(Message2) {
		console.log(Message2);
	})

Output:

Run Code Snippet

This is an example of the Promise rejected:

Code Snippet:

var Promise = new Promise(function(resolve, reject) {
	reject('The JavaScript Promise Rejected')
})
Promise
	.then(function(Message1) {
		console.log(Message1);
	}, function(Message2) {
	//error handler function is invoked
		console.log(Message2);
	})

Output:

Run Code Snippet

.catch() method:

The compiler invokes the catch() when an error has occurred or rejected the JS Promise during the execution. Users can use this as an Error Handler at any line of the JavaScript code whenever there is a possibility of finding an error.

Syntax:

.catch(function(error){
        //handle error
    })

This is an example of the Promise rejected:

Code Snippet:

var Promise = new Promise(function(resolve, reject) {
	reject('The JavaScript Promise Rejected')
})
Promise
	.then(function(Message1) {
		console.log(Message1);
	})
	.catch(function(Message2) {
	//error handler function is invoked
		console.log(Message2);
	});

Output:

Run Code Snippet

This is an example of the Promise rejected showing an error message:

Code Snippet:

var Promise = new Promise(function(resolve, reject) {
	throw new Error('Here, we are getting an error message')
})
Promise
	.then(function(Message1) {
		console.log(Message1);
	})
	.catch(function(Message2) {
	//error handler function is invoked
		console.log(Message2);
	});

Output:

Run Code Snippet

What are the applications of the JavaScript Promise?

The three most significant applications of the JS Promise are as follows:

  • Users can use the Promise object for asynchronous handling of events.
  • Users can use the JS Promises to deal with asynchronous HTTP requests.
  • The Promise can be advantageous and efficient while handling errors in the JavaScript program.

Conclusion:

JavaScript is a popular web development scripting language that provides multiple methods, objects, and functions for its convenient working. The JavaScript Promise is one of those objects that handle all the asynchronous actions and operations. We hope this article has given all the ideas on JavaScript Promise and how it works with the following code snippets. Also, we have discussed the advantage and applications of the Promise.


×