Nearby lessons

17 of 22

JavaScript: Promise

📌 What is a Promise?

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It has three states: pending, fulfilled, and rejected.

1️⃣ Basic Promise Using Variable

Here, a boolean variable controls whether the Promise resolves or rejects.

Example02
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

2️⃣ Promise Using Function with Parameter

A function returns a Promise, which resolves or rejects based on the parameter value.

Example03
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

3️⃣ Handling Resolved and Rejected Promises

.then() handles resolved results, and .catch() handles rejections.

Example04
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

4️⃣ Display 'Fetching...' Before Promise Resolves

Use console.log() before the asynchronous task to simulate a real-world fetch operation.

Example05
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

5️⃣ Simplified Promise with Chaining

Combining .then() and .catch() directly improves code readability.

Example06
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

6️⃣ Real-Life Example with AJAX (jQuery)

This Promise wraps a jQuery AJAX call to simulate real-world API usage.

Example07
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3