#atom
Content:
Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They provide a cleaner and more structured way to handle asynchronous tasks compared to callbacks, avoiding issues like "callback hell." Promises are widely used in modern JavaScript for tasks like API calls, file I/O, and timers.
Key Concepts:
-
What is a Promise?
- A Promise is an object that can be in one of three states:
- Pending: The initial state; the operation is still in progress.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
- Once a Promise is fulfilled or rejected, it is considered "settled" and cannot change its state.
- A Promise is an object that can be in one of three states:
-
Creating a Promise:
- A Promise is created using the
Promise
constructor, which takes a function (called the executor) with two arguments:resolve
andreject
. - Example:
const myPromise = new Promise((resolve, reject) => { setTimeout(() => { const success = true; if (success) { resolve("Operation succeeded!"); } else { reject("Operation failed!"); } }, 1000); });
- A Promise is created using the
-
Consuming a Promise:
- Promises are consumed using
.then()
for fulfillment,.catch()
for rejection, and.finally()
for cleanup. - Example:
myPromise .then((result) => { console.log(result); // "Operation succeeded!" }) .catch((error) => { console.error(error); // "Operation failed!" }) .finally(() => { console.log("Promise settled."); });
- Promises are consumed using
-
Chaining Promises:
- Promises can be chained to perform sequential asynchronous operations.
- Example:
fetchData() .then((data) => processData(data)) .then((processedData) => saveData(processedData)) .catch((error) => console.error(error));
Promise Static Methods:
-
Promise.all()
:- Takes an array of Promises and returns a single Promise that resolves when all input Promises have resolved, or rejects if any input Promise rejects.
- Example:
const promise1 = Promise.resolve(1); const promise2 = Promise.resolve(2); Promise.all([promise1, promise2]) .then((results) => { console.log(results); // [1, 2] }) .catch((error) => { console.error(error); });
-
Promise.race()
:- Returns a Promise that resolves or rejects as soon as one of the input Promises resolves or rejects.
- Example:
const promise1 = new Promise((resolve) => setTimeout(resolve, 500, "First")); const promise2 = new Promise((resolve) => setTimeout(resolve, 1000, "Second")); Promise.race([promise1, promise2]) .then((result) => { console.log(result); // "First" });
-
Promise.allSettled()
:- Returns a Promise that resolves after all input Promises have settled (either fulfilled or rejected), providing an array of results.
- Example:
const promise1 = Promise.resolve(1); const promise2 = Promise.reject("Error"); Promise.allSettled([promise1, promise2]) .then((results) => { console.log(results); // [ // { status: "fulfilled", value: 1 }, // { status: "rejected", reason: "Error" } // ] });
-
Promise.any()
:- Returns a Promise that resolves as soon as one of the input Promises fulfills. If all Promises reject, it rejects with an
AggregateError
. - Example:
const promise1 = Promise.reject("Error 1"); const promise2 = Promise.resolve("Success"); Promise.any([promise1, promise2]) .then((result) => { console.log(result); // "Success" });
- Returns a Promise that resolves as soon as one of the input Promises fulfills. If all Promises reject, it rejects with an
-
Promise.resolve()
:- Creates a Promise that is already resolved with a given value.
- Example:
const resolvedPromise = Promise.resolve("Resolved!"); resolvedPromise.then((result) => console.log(result)); // "Resolved!"
-
Promise.reject()
:- Creates a Promise that is already rejected with a given reason.
- Example:
const rejectedPromise = Promise.reject("Rejected!"); rejectedPromise.catch((error) => console.error(error)); // "Rejected!"
Promise Prototype Methods:
-
.then()
:- Attaches fulfillment and rejection handlers to the Promise.
- Signature:
then(onFulfilled?: (value: T) => TResult, onRejected?: (reason: any) => TResult): Promise<TResult>;
-
.catch()
:- Attaches a rejection handler to the Promise.
- Signature:
catch(onRejected?: (reason: any) => TResult): Promise<TResult>;
-
.finally()
:- Attaches a handler that runs when the Promise is settled, regardless of its outcome.
- Signature:
finally(onFinally?: () => void): Promise<T>;
Example: Combining Promises
const fetchUser = () => Promise.resolve({ id: 1, name: "Alice" });
const fetchPosts = () => Promise.resolve(["Post 1", "Post 2"]);
Promise.all([fetchUser(), fetchPosts()])
.then(([user, posts]) => {
console.log("User:", user);
console.log("Posts:", posts);
})
.catch((error) => {
console.error("Error:", error);
});
Linked Cards:
- Asynchronous JavaScript: Promises are a core concept for handling async operations.
- Callbacks in JavaScript: Promises provide a cleaner alternative to callbacks.
- Async/Await in JavaScript:
async/await
syntax simplifies working with Promises. - Error Handling in JavaScript: Promises handle errors using
.catch()
andtry/catch
withasync/await
. - Functions in JavaScript: Promises are often used with functions for async tasks.
Tags: #JavaScript #Promises #AsynchronousProgramming #PromiseAll #ErrorHandling #AsyncAwait
Connections:
Sources: