All about promises!

Here is a deep dive into all the abilities of promises in ES6+. A Promise in JavaScript is an object representing the eventual completion (or failure) of an asynchronous operation. It has several built-in functions that allow handling asynchronous tasks efficiently. Let's dive deep into all the functions of a Promise: 1. Creating a Promise A Promise is created using the new Promise constructor: const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve("Success!"); }, 2000); }); The executor function takes two arguments: resolve(value): Marks the Promise as fulfilled and returns a value. reject(error): Marks the Promise as rejected with an error. Here's an example of a promise in action: function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { const success = true; // Change this to false to simulate an error if (success) { resolve("Data fetched successfully!"); } else { reject("Error fetching data."); } }, 2000); // Simulate network delay }); } fetchData() .then((result) => { console.log(result); // "Data fetched successfully!" }) .catch((error) => { console.error(error); // "Error fetching data." }); Methods in promises resolve reject all allSettled race any Resolve

Feb 12, 2025 - 06:49
 0
All about promises!

Here is a deep dive into all the abilities of promises in ES6+.

A Promise in JavaScript is an object representing the eventual completion (or failure) of an asynchronous operation. It has several built-in functions that allow handling asynchronous tasks efficiently.

Let's dive deep into all the functions of a Promise:

1. Creating a Promise

A Promise is created using the new Promise constructor:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Success!");
  }, 2000);
});

The executor function takes two arguments:

  1. resolve(value): Marks the Promise as fulfilled and returns a value.

  2. reject(error): Marks the Promise as rejected with an error.

Here's an example of a promise in action:

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const success = true; // Change this to false to simulate an error
      if (success) {
        resolve("Data fetched successfully!");
      } else {
        reject("Error fetching data.");
      }
    }, 2000); // Simulate network delay
  });
}

fetchData()
  .then((result) => {
    console.log(result); // "Data fetched successfully!"
  })
  .catch((error) => {
    console.error(error); // "Error fetching data."
  });

Methods in promises

  1. resolve
  2. reject
  3. all
  4. allSettled
  5. race
  6. any

Resolve