𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀
A Promise represents the result of an asynchronous task.
You use Promises for API calls, database queries, and file reading.
A Promise has three states:
- Pending: The task is still running.
- Fulfilled: The task finished successfully.
- Rejected: The task failed with an error.
The structure looks like this:
const promise = new Promise((resolve, reject) => { // The executor runs immediately });
You handle the results with these methods:
- .then(): Runs when the promise succeeds.
- .catch(): Runs when the promise fails.
- .finally(): Runs when the task ends regardless of the outcome.
Important rules to remember:
- The first outcome wins. If you call resolve() and then reject(), the resolve wins.
- The executor function runs synchronously.
- Using async and await makes your code easier to read than using .then().
Handling multiple promises:
- Promise.all(): This follows a fail-fast approach. If one promise fails, the whole group fails.
- Promise.allSettled(): This waits for every promise to finish. It returns the results even if some tasks fail.
Summary:
- Promise: An asynchronous result handler.
- resolve: Marks success.
- reject: Marks failure.
- async/await: A cleaner way to write promises.
- Promise.all: Stops on the first error.
- Promise.allSettled: Completes all tasks.
