πŸ”— JavaScript Promises - Complete Guide

Learn All in One

πŸ“Œ What is a Promise?

A Promise is an object in JavaScript that represents a value which may be available now, later, or never. It’s used to handle asynchronous operations.

πŸ” Understanding async and await

async/await in Detail

In JavaScript, async is used to declare an asynchronous function. It always returns a Promise.

The await keyword is used inside an async function to pause execution until a Promise is resolved, making asynchronous code easier to read.

async function getData() {
  const response = await fetch("https://api.example.com/data");
  const result = await response.json();
  console.log(result);
}
getData();
    

Use Case: Ideal for handling API calls, timeouts, and non-blocking code.

F

🧾 Syntax of a Promise


const promise = new Promise((resolve, reject) => {
  // async task here
});
      

πŸ”„ States of a Promise

πŸ§ͺ Example with Breakdown


const fetchData = () => {
  return new Promise((resolve, reject) => {
    let success = true;
    setTimeout(() => {
      if (success) {
        resolve("βœ… Data fetched successfully");
      } else {
        reject("❌ Failed to fetch data");
      }
    }, 1000);
  });
};

fetchData()
  .then(response => console.log(response))
  .catch(error => console.log(error))
  .finally(() => console.log("Operation completed"));
      

πŸ” Breakdown:

πŸ“– Promise Methods

Study in Detail

βš™οΈ What is async and await?


async function getInfo() {
  try {
    let res = await fetch("https://jsonplaceholder.typicode.com/users/1");
    let data = await res.json();
    console.log(data);
  } catch (err) {
    console.error("Error fetching:", err);
  }
}
      

Note: await can only be used inside async functions.

🧠 Summary

Promise Practice worksheet

Open Worksheet