Open In App

JavaScript Promise

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

JavaScript Promises 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: It 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: It 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads