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

JavaScript Promise

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript promises might sound a bit complicated at first, but once you get a clear understanding of them, they make working with code that takes time to complete, like fetching data from a website or waiting for a timer, much easier to manage. Let’s break down what promises are and how you can use them.

What is a Promise?

A promise in JavaScript is like a container for a future value. It is a way of saying, “I don’t have this value right now, but I will have it later.” Imagine you order a book online. You don’t get the book right away, but the store promises to send it to you. While you wait, you can do other things, and when the book arrives, you can read it.

In the same way, a promise lets you keep working with your code while waiting for something else to finish, like loading data from a server. When the data is ready, the promise will deliver it.

How Does a Promise Work?

A promise can be in one of three states:

  • Pending: The promise is waiting for something to finish. For example, waiting for data to load from a website.
  • Fulfilled: The promise has been completed successfully. The data you were waiting for is now available.
  • Rejected: The promise has failed. Maybe there was a problem, like the server not responding.

When you create a promise, you write some code that will eventually tell the promise whether it was successful (fulfilled) or not (rejected).

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.

Creating a Promise

Let’s see how to create the promise in JavaScript:

Here we have created a new promise using the Promise constructor. Inside the promise, there are two functions: resolve and reject. If everything goes well, we call resolve and pass the result. If something goes wrong, we call reject and pass an error message.

JavaScript
let myPromise = new Promise(function(resolve, reject) {
  // some code that takes time, like loading data
  let success = true; // change this to false to check error

  if (success) {
    resolve("The data has loaded successfully!");
  } else {
    reject("There was an error loading the data.");
  }
});

Using a Promise

Once you have a promise, you can use it to do something when it’s fulfilled or rejected. You can do this using two methods: then and catch.

JavaScript
myPromise.then(function(message) {
// This runs if the promise is fulfilled
  console.log(message); 
}).catch(function(error) {
// This runs if the promise is rejected
  console.log(error); 
});

Here’s what’s happening:

  • The then method is called when the promise is fulfilled. It takes a function as an argument, which will run when the promise is successful.
  • The catch method is called when the promise is rejected. It also takes a function, which will run if there’s an error.

So, if the promise is successful, you will see “The data has loaded successfully!” in the console. If there’s an error, you will see “There was an error loading the data.”

Example of Using Promise

We will 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

Now, that we have learned about how we can create promise let’s see promise consumers that how we can consume them.

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 1: 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 2: 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 1: 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

Why Use Promises?

Before promises, handling code that took time to complete, like loading data, was more difficult. You had to use something called callbacks, which could get messy and hard to follow, especially when you had to do several things in a row. Promises make this easier by providing a clear way to work with asynchronous code (code that doesn’t run right away). They help you write code that is easier to read and maintain.

Chaining Promises

Sometimes, you need to do several things one after another, like load some data, process it, and then display it. With promises, you can do this by chaining then methods:

JavaScript
fetchData().then(function(data) {
  console.log("Data received:", data);
  // Suppose this is another function that returns a promise
  return processData(data); 
}).then(function(processedData) {
  console.log("Processed data:", processedData);
}).catch(function(error) {
  console.log("Error:", error);
});

In this example:

  • The first then gets the data and passes it to processData.
  • processData returns another promise.
  • The second then handles the result of processData.
  • If anything goes wrong along the way, the catch handles the error.

Supported Browsers:

FAQs – JavaScript Promise

How do Promises work in JavaScript?

Promises use then() and catch() methods to handle asynchronous results, allowing chaining of operations.

What are the states of a Promise?

Promises have three states: pending (initial state), fulfilled (successful completion), and rejected (failure).

How do you create a Promise in JavaScript?

Promises are created using the new Promise() constructor, which takes an executor function with resolve and reject parameters

What is Promise chaining?

Promise chaining is the practice of sequentially executing asynchronous operations using multiple then() calls on a Promise.

Can Promises be canceled in JavaScript?

Promises cannot be canceled natively, but techniques like using an external flag or a custom implementation can simulate cancellation.

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
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
JavaScript Promise constructor
JavaScript Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. Promise constructor in JavaScript is mainly used to wrap functions that do not already support promises. Syntax: new Promise(e
2 min read
JavaScript Promise finally() Method
The finally() method of the Promise object is used to return a Promise when a Promise is settled, that is, it is either fulfilled or rejected. A Promise is a JavaScript object which generates a value after an asynchronous function executes successfully. When it does not execute successfully due to a timeout, then it generates an error. It can be us
2 min read
JavaScript Program that returns true if an object looks like a Promise
In JavaScript, Promises are objects that link the producing and the consuming code together. While in simple terms a Promise in JavaScript means the same as a promise in real life. Whenever a Promise is created there are 3 conditions or would rather say results that we can expect: resolverejectpending As the above names suggest, whenever a Promise
2 min read
JavaScript Promise Chaining
In this article, we will discuss how to perform Promise Chaining in JavaScript. A Promise is basically an object which represents the completion (or failure) of an asynchronous operation along with its result. A promise has 3 types of states and based upon these states, the promise executes the results. Pending: This state represents either an init
3 min read
How to convert an asynchronous function to return a promise in JavaScript ?
In this article, we will learn how to convert an asynchronous function to return a promise in JavaScript. Approach: You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need to return the promise as an output from that async
3 min read
Implement polyfill for Promise.all() method in JavaScript
The task is to write a polyfill for Promise.all methods in javascript. What is a Polyfill? A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because the older version of the browser you are using, or the new version of the browser does not have that feature. What is Promise.
4 min read
Explain Promise.race() with async-await in JavaScript
In this article, we will try to understand how we may implement Promise.race() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand how we may implement Promise.race() method. This method is one of the most commonly used promise methods that state whichev
3 min read
Explain Promise.any() with async-await in JavaScript
In this article, we will try to understand how to implement the Promise.any() method with async-await in JavaScript using some theoretical explanations followed by some coding examples as well. Let us firstly quickly understand the working of Promise.any() method with some theoretical examples (including the syntax of declaring this particular meth
4 min read
Promise reject does not propagate the error correctly in JavaScript
In this article, we will try to understand why Promise's reject() method doesn't propagate the error correctly, and later we will see the solution for the same along with certain theoretical explanations and coding examples. Let us first have a look into the following section quickly which enlightens us on the syntax of how a promise will be create
4 min read
How to create a global Promise Rejection Handler in JavaScript ?
In this article, we will try to understand firstly how we create a Rejected Promise, and later we will see how we may create a Global Promise Rejection Handler which will try to handle (somehow) that Rejected Promise created earlier in JavaScript. Let us first try to understand how we create a Promise (with Rejected State) in JavaScript using the f
2 min read
JavaScript Promise constructor Property
JavaScript Promise constructor property is used to return the Promise constructor function for the object. The function which is returned by this property is just a reference to this function, not a Promise containing the function's name. The JavaScript number constructor, string constructor, and boolean constructor return function Number() { [nati
1 min read
JavaScript Promise any() Method
JavaScript Promise any() method is a static method that takes an array of promises as a parameter and returns the first fulfilled promise. It returns a rejected value when all of the promises in the array return rejects or if the array is empty. When all the promises are rejected an AggregateError is returned which contains the reason for rejection
2 min read
JavaScript Promise catch() Method
JavaScript Promise catch() method is called whenever a promise is rejected. This method itself returns a promise so it can also be used to chain promises. This method is used for error handling. This method is mainly used after .then to chain a promise and handle reject condition. This method internally calls .then with undefined and rejected condi
2 min read
How to Synchronously determine a JavaScript Promise's State
Handling asynchronous operations in JavaScript can be challenging. However, Promises has made this task easier by providing a more elegant and better error management solution. Although Promise-based code is primarily designed to work asynchronously, there may be instances where you need to synchronously determine a Promise's state for various reas
3 min read
Explain Promise.allSettled() with async-await in JavaScript
In this article, we will try to understand how we may implement the Promise.allSettled() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand about Promise.allSettled() method. This method is one of the most common methods available under the Promise obje
3 min read
JavaScript promise reject() Method
The Promise.reject() method is used to return a rejected Promise object with a given reason for rejection. It is used for debugging purposes and selective error-catching. The catch() method can be used for logging the output of the reject() method to the console that is catch() method acts as a career that carries the rejected message from the Prom
3 min read
How to access the Value of a Promise in JavaScript
In this article, we will see how to access the value of Promise in JavaScript. The Promise is a feature of ES6 introduced in 2015. The concept of Promises is generally used when we want to work asynchronously. The value of a Promise can be accessed in JavaScript using the following methods. Table of Content Using .then( ) MethodUsing the Async/Awai
2 min read
JavaScript Promise allSettled() Method
Promise.allSettled() method in JavaScript is used to handle multiple promises concurrently and return a single promise. This promise is fulfilled with an array of promise state descriptors, each describing the outcome of the corresponding promise in the input array. Unlike Promise.all(), Promise.allSettled() does not short-circuit when one of the p
2 min read
How to Check if a Value is a Promise in JavaScript ?
To check if a value is a Promise in JavaScript, we can use the instanceof operator. Promises are a specific type of object, and this operator allows you to check if an object is an instance of a particular class or constructor function. so we will use this to check whether the given value is a promise or not. Example: Here, the isPromise function c
1 min read
How to Implement a Custom Promise in JavaScript ?
A custom Promise in JavaScript encapsulates asynchronous operations. It takes two parameters, resolves and rejects functions, and executes an async task. Resolve is called on success with the result, while reject is called on failure with an error. Table of Content Using Class SyntaxUsing Factory FunctionUsing Class SyntaxIn this approach, we are c
3 min read
Where is rejected property stored for a Promise in JavaScript ?
Rejected property for a Promise in JavaScript is Stored under the promise's internal object's property named PromiseState, the rejected property of the promise is stored, and later when we have implemented catch in order to make our promise fulfilled then that PromiseState property's value becomes Fulfilled. Now lets see this with an example, Since
1 min read