Home > Web Front-end > JS Tutorial > Promise in Javascript

Promise in Javascript

Barbara Streisand
Release: 2024-10-20 14:34:02
Original
529 people have browsed it

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.

Promise in Javascript
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:

Promise in Javascript

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:

Promise in Javascript

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
  });

Copy after login

Example:

Promise in Javascript

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

The above is the detailed content of Promise in Javascript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template