JavaScript Promises: resolve, reject, and Chaining


Promises in JavaScript are used to handle asynchronous operations like API calls, file reading, or timers — without falling into callback hell.



What is a Promise?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.

Promise States:

  • Pending – initial state
  • Fulfilled – operation completed (resolve)
  • Rejected – operation failed (reject)


Creating a Basic Promise

const myPromise = new Promise((resolve, reject) => {
  let success = true;

  if (success) {
    resolve(" Promise fulfilled!");
  } else {
    reject("Promise rejected.");
  }
});


Handling Promises with .then() and .catch()

myPromise
  .then(result => {
    console.log(result); //  Promise fulfilled!
  })
  .catch(error => {
    console.error(error); //  Promise rejected.
  });


Promise Chaining

You can chain .then() calls to perform multiple asynchronous tasks in sequence.

function delayTask(msg, time) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(msg);
      resolve();
    }, time);
  });
}

delayTask("Step 1", 1000)
  .then(() => delayTask("Step 2", 1000))
  .then(() => delayTask("Step 3", 1000));

Output

Step 1
Step 2
Step 3


Using .catch() for Errors

const errorPromise = new Promise((resolve, reject) => {
  reject("Something went wrong!");
});

errorPromise
  .then(data => console.log(data))
  .catch(err => console.error("Caught error:", err));


Real-World Use Case (e.g., Fetching API Data)

fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log("Post Title:", data.title))
.catch(error => console.error("Fetch error:", error));