DEV Community

Diana
Diana

Posted on

Promise in Javascript

Promise

represents a value that may be available now, or in the future, or never.
Promise Life Cycle:

  • Pending: The function starts to work.

  • Fulfilled: The operation completed successfully, and we have a result value.

  • Rejected: The operation failed, and we have an error object.

Syntax of a Promise:

A promise is created using the new Promise constructor, which takes a function with two arguments: resolve and reject.

Image description
In the code snippet, we have a function called getUser, which returns a new Promise (a promise object that has methods to handle asynchronous operations).

Inside the Promise constructor, we have a setTimeout function that simulates an asynchronous operation, such as fetching data from a database. The promise has two key methods passed to it:

  • resolve: This is called when the operation is successful. In this case, if id === 1, it returns a mock user object { id: 1, name: "Diana", email: "Diana@test.com" }.

  • reject: This is called when the operation fails. If the id is not 1, the promise is rejected with an error message "User not found...".

The resolve and reject functions act like return statements in the context of promises, allowing the caller to handle the success or failure of the operation.

Chaining Promises

Promises can be chained, allowing you to perform a series of asynchronous operations in sequence:

Image description

In this example, we are chaining multiple promises to simulate fetching data step by step.

  • First, we call getUser(1) to get the user data. If it works, we move to the next step.

  • Second, we take the user.id and use it to get the orders for that user by calling getOrders(user.id).

-Third, we pick the second order (orders[1]) from the list and get its details using getOrderDetails(orders[1]).

If anything goes wrong at any point (like the user not being found or orders missing), the error will be caught in the .catch() block and displayed.

Simple Breakdown:

  • You ask for a user.
  • If you find the user, you ask for their orders.
  • If you get the orders, you ask for details about one of the orders.
  • If anything goes wrong (like the user or orders not being found), - it will show an error.

result:

Image description

This approach makes it easier to work with asynchronous tasks in a clean, step-by-step way instead of having messy code.

Promise Methods:

Promise.all(): Executes multiple promises in parallel and waits until all of them are resolved.

Promise.all([promise1, promise2])
  .then((results) => {
    console.log(results);  // Array of all fulfilled values
  });

Enter fullscreen mode Exit fullscreen mode

Example:

Image description

(I recommend to read and compare this approach to callbacks)

Top comments (0)