Skip to main content

Command Palette

Search for a command to run...

πŸ”Ή Promises in JavaScript

Published
β€’2 min readβ€’View as Markdown

πŸ“Œ What is a Promise?

A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. Promises provide a cleaner, more manageable alternative to traditional callback-based asynchronous programming.

βœ… Advantages of Promises over Callbacks:

  • Avoid callback hell (nested callbacks).

  • Better error handling using .catch().

  • Support for chaining asynchronous operations using .then().


πŸ“˜ Promise States:

A Promise can be in one of three states:

  1. Pending – The initial state, neither fulfilled nor rejected.

  2. Fulfilled – The operation completed successfully.

  3. Rejected – The operation failed.


🧩 Basic Syntax:

jsCopyEditconst promise = new Promise((resolve, reject) => {
  // async operation
});
  • resolve(value) – Called when the async operation succeeds.

  • reject(error) – Called when the async operation fails.


πŸ•’ Example: Promisify setTimeout

πŸ”§ Code to Create a Promisified Timeout Function:

jsCopyEditfunction setTimeoutPromisified(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

πŸ’‘ Explanation:

  • setTimeoutPromisified returns a Promise that resolves after ms milliseconds.

  • setTimeout is used internally, but instead of using a callback directly, the resolution is handled via resolve.


πŸ”” Using the Promisified Function:

jsCopyEditfunction callback() {
  console.log("3 seconds have passed");
}

setTimeoutPromisified(3000).then(callback);

🧠 Breakdown:

  • After 3 seconds, the Promise resolves.

  • .then(callback) is called, executing the callback function.


⚠️ Tips:

  • Always handle possible errors using .catch() in real-world applications.

  • Promises are chainable, so you can do:

      jsCopyEditsetTimeoutPromisified(1000)
        .then(() => console.log("1 second passed"))
        .then(() => setTimeoutPromisified(2000))
        .then(() => console.log("2 more seconds passed"));