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.

Code Example
PREVIEW READY
Loading Editor...
Live Preview

2️⃣ Promise Using Function with Parameter

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

3️⃣ Handling Resolved and Rejected Promises

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

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

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

5️⃣ Simplified Promise with Chaining

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

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

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!AJS - Promise.all()