The Wayback Machine - https://web.archive.org/web/20240528225128/https://www.geeksforgeeks.org/javascript-promise/
Open In App

JavaScript Promise

Last Updated : 28 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript Promises used to simplify managing multiple asynchronous operations, preventing callback hell and unmanageable code. They represent future values, associating handlers with eventual success or failure, resembling synchronous methods by postponing value delivery until later.

Syntax:

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

Parameters

  • The promise constructor takes only one argument which is a callback function
  • The callback function takes two arguments, resolve and reject
    • Perform operations inside the callback function and if everything went well then call resolve.
    • If desired operations do not go well then call reject.

A Promise has four states:

  1. fulfilled: Action related to the promise succeeded
  2. rejected: Action related to the promise failed
  3. pending: Promise is still pending i.e. not fulfilled or rejected yet
  4. settled: Promise has been fulfilled or rejected

Example 1: In this example we create a promise comparing two strings. If they match, resolve; otherwise, reject. Then, log success or error accordingly. Simplifies asynchronous handling in JavaScript.

Javascript
let promise = new Promise(function (resolve, reject) {
    const x = "geeksforgeeks";
    const y = "geeksforgeeks"
    if (x === y) {
        resolve();
    } else {
        reject();
    }
});

promise.
    then(function () {
        console.log('Success, You are a GEEK');
    }).
    catch(function () {
        console.log('Some error has occurred');
    }); 

Output
Success, You are a GEEK

Promise Consumers: Promises can be consumed by registering functions using .then and .catch methods.

1. Promise then() Method:

Promise method is invoked when a promise is either resolved or rejected. It may also be defined as a carrier that takes data from promise and further executes it successfully.

Parameters: It takes two functions as parameters.

  • The first function is executed if the promise is resolved and a result is received.
  • The second function is executed if the promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method

Syntax:

.then(function(result){
        //handle success
}, function(error){
        //handle error
})

Example 2: This example shows how the then method handles when a promise is resolved

Javascript
let promise = new Promise(function (resolve, reject) {
    resolve('Geeks For Geeks');
})

promise
    .then(function (successMessage) {
        //success handler function is invoked 
        console.log(successMessage);
    }, function (errorMessage) {
        console.log(errorMessage);
    }); 

Output
Geeks For Geeks

Example 3: This example shows the condition when a rejected promise is handled by second function of then method

Javascript
let promise = new Promise(function (resolve, reject) {
    reject('Promise Rejected')
})

promise
    .then(function (successMessage) {
        console.log(successMessage);
    }, function (errorMessage) {
        //error handler function is invoked 
        console.log(errorMessage);
    }); 

Output
Promise Rejected

2. Promise catch() Method:

Promise catch() Method is invoked when a promise is either rejected or some error has occurred in execution. It is used as an Error Handler whenever at any step there is a chance of getting an error.

Parameters: It takes one function as a parameter.

  • Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )

Syntax:

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

Examples 4: This example shows the catch method handling the reject function of promise.

Javascript
let promise = new Promise(function (resolve, reject) {
    reject('Promise Rejected')
})

promise
    .then(function (successMessage) {
        console.log(successMessage);
    })
    .catch(function (errorMessage) {
        //error handler function is invoked 
        console.log(errorMessage);
    }); 

Output
Promise Rejected

Supported Browsers:

We have a complete list of Javascript Promise methods, to check those please go through the Javascript Promise Reference article.



Previous Article
Next Article

Similar Reads

How does Promise.all() method differs from Promise.allSettled() method in JavaScript ?
In this article, we will first understand in brief the Promise.all() as well as Promise.allSettled() methods and then we will try to visualize how they differ from each other through some theoretical as well as some coding examples. Both Promise.all() and Promise.allSettled() methods are the methods of a Promise object (which is further a JavaScrip
4 min read
How does Promise.any() method differs from Promise.race() method in JavaScript ?
In this article, we will first try to understand how we may declare or use Promise.any() and Promise.race() methods followed by some facts which will eventually help us to understand how they differ from each other (through theoretical as well as coding examples). Let us first quickly understand in brief about both the methods followed by their syn
5 min read
Difference Between Promise.resolve() & Promise.reject() methods in JavaScript
Promise.resolve() and Promise.reject() are both methods provided by the Promise object in JavaScript. They serve different purposes in handling asynchronous operations: Promise.resolve():Creates a new Promise object that is resolved with the provided value or a resolved Promise object if the provided value is already a Promise.Example:const resolve
1 min read
How to call promise inside another promise in JavaScript ?
In JavaScript, to call promise inside another promise we first declare a promise using its basic syntax and further execute this promise then create another which is to be called inside the previous promise for its execution. Promise is basically a JavaScript object which is responsible for handling all the asynchronous operations or activities lik
3 min read
Different error handling in "Promise.resolve" vs "new Promise" constructor
In JavaScript, there are two ways to create a promise: using the Promise.resolve method or using the new Promise constructor. While both ways achieve the same result, they handle errors differently. Promise.resolve: The Promise.resolve method takes in a value and returns a promise that is resolved with that value. If the value is a promise, the ret
3 min read
Why Promise.all doesn't reject when a non-promise throws an error ?
In this article, we will talk about why Promise.all() method does not get rejected when one of the non-input promises throws an error, and in which cases the Promise.all() does get rejected. Promise.all() is a method that returns a promise. It takes an array of promises as its argument and returns a single promise, which gets rejected even if one o
3 min read
JavaScript Promise all() Method
The Promise.all() method is actually a method of the Promise object (which is also an object under JavaScript used to handle all the asynchronous operations), that takes an array of promises(an iterable) as input. It returns a single Promise that resolves when all of the promises passed as an iterable, which have resolved, or when the iterable cont
5 min read
How to delay a loop in JavaScript using async/await with Promise ?
Given below is a JavaScript code snippet which is basically described how to delay a loop in JavaScript using async/await. In this article, we are using JavaScript either the web browser or Node.js. We all face a difficult situation in delaying a loop in JavaScript unlike C++ where we have sleep() function, but there is nothing like this in JavaScr
2 min read
JavaScript Promise race() Method
The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise. We may think of this particular method as in the form of a real-life example where several people are running in a race whosoever wins comes first wins the race, the same
2 min read
JavaScript Promise Reference
JavaScript Promise is used to handle asynchronous operations JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous op
2 min read