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.
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.
Promises can be chained, allowing you to perform a series of asynchronous operations in sequence:
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.
result:
This approach makes it easier to work with asynchronous tasks in a clean, step-by-step way instead of having messy code.
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 });
Example:
(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!