JavaScript Promises

JavaScript Promises

JavaScript Promises

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation. It helps handle asynchronous code without callback hell.

🔹 Why Use Promises?

Avoids Callback Hell (nested callbacks)
Better error handling with .catch()
Can chain multiple async operations

🔹 Creating a Basic Promise

A Promise has three states:

  1. Pending – Initial state
  2. Fulfilled – When resolved successfully (resolve())
  3. Rejected – When an error occurs (reject())
let myPromise = new Promise((resolve, reject) => { let success = true; // Change to false to test rejection setTimeout(() => { if (success) { resolve("Promise resolved successfully!"); } else { reject("Promise rejected!"); } }, 2000); }); myPromise .then((message) => console.log("✅ Success:", message)) .catch((error) => console.log("❌ Error:", error));

Output (after 2 seconds):

Success: Promise resolved successfully!

✔ If success is false, it will go to .catch() instead.

🔹 Chaining Promises

Promises can be chained to handle multiple asynchronous steps in order.

function step1() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 1 complete"); resolve(); }, 1000); }); } function step2() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 2 complete"); resolve(); }, 1000); }); } function step3() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 3 complete"); resolve(); }, 1000); }); } // Promise chaining step1() .then(step2) .then(step3) .then(() => console.log("All steps completed"));

Output (with delays):

Step 1 complete Step 2 complete Step 3 complete All steps completed

Each step executes after the previous one completes.

🔹 Handling Errors with .catch()

If an error occurs in any .then(), .catch() will handle it.

let myPromise = new Promise((resolve, reject) => { setTimeout(() => { reject("Something went wrong!"); }, 1000); }); myPromise .then((message) => console.log("✅ Success:", message)) .catch((error) => console.log("❌ Error:", error));

Output:

Error: Something went wrong!

.catch() prevents the app from crashing.

🔹 Using Promise.all()

Promise.all() runs multiple promises in parallel and waits for all to resolve.

let promise1 = new Promise((resolve) => setTimeout(() => resolve("Task 1"), 2000)); let promise2 = new Promise((resolve) => setTimeout(() => resolve("Task 2"), 1000)); Promise.all([promise1, promise2]).then((results) => { console.log("✅ All tasks completed:", results); });

Output (after 2 seconds):

All tasks completed: ["Task 1", "Task 2"]

If any promise fails, Promise.all() will reject.

🔹 Using Promise.race()

Promise.race() returns the result of the first resolved promise.

let promise1 = new Promise((resolve) => setTimeout(() => resolve("Fast Task"), 1000)); let promise2 = new Promise((resolve) => setTimeout(() => resolve("Slow Task"), 3000)); Promise.race([promise1, promise2]).then((result) => { console.log("✅ First completed task:", result); });

Output (after 1 second):

✅ First completed task: Fast Task

The fastest promise wins.

🔹 Using async/await with Promises

Instead of .then(), use async/await for cleaner code.

function fetchData() { return new Promise((resolve) => { setTimeout(() => resolve("Data loaded"), 2000); }); } async function load() { console.log("Fetching data..."); let data = await fetchData(); console.log("✅", data); } load();

Output:

Fetching data... (Data appears after 2 seconds) ✅ Data loaded

Makes async code look synchronous!

🔹 Summary

✔ A Promise handles asynchronous operations
.then() for success, .catch() for errors
Chaining helps avoid callback hell
Promise.all() waits for all, Promise.race() returns first
Use async/await for cleaner code

🚀 Need more details? Let me know! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close