Trusted answers to developer questions

What are promises in JavaScript?

Checkout some of our related courses
JavaScript Fundamentals Before Learning React
Beginner

In JavaS​cript, callback functions were initially used to handle asynchronous operations. However, callbacks were limited in terms of functionality and often led to confusing code, so, ​promises were introduced to cater to these problems. According to MDN, “the Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.”

A promise object has one of three states:

  • pending: is the initial state.
  • fulfilled: indicates that the promised operation was successful.
  • rejected: indicates that the promised operation was unsuccessful.​
svg viewer

Code

Creating a simple promise

  1. A promise is created using a constructor that takes a call back function with two arguments (line 1).
  2. The code needed to perform the promised task is written. In this example, it is assumed that the code executes successfully (line 2).
  3. If the task is successful, the promise is resolved. In this example, the optional parameter “The promised task was performed successfully” is passed (lines 4-5).
  4. If the task is unsuccessful, then the promise is rejected. In this example, an optional parameter is passed (lines 6-7).
  5. The then() method is called when the promise is resolved, ​and the catch() method is called if the promise is rejected or if there was an error during the code execution (lines 10-11).
Console

Using Promise.all()

The Promise.all() method returns a single promise that resolves when all of the passed-in promises have resolved. It rejects if one of the promises is rejected.

Console

Using Promise.race()

The Promise.race() method returns a promise that resolves or rejects as soon as one of the promises resolves or rejects. The fromRes method​ contains the value from the promise that is resolved first.

Console

RELATED TAGS

promise
javascript
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?