DEV Community

Chirath Nissanka
Chirath Nissanka

Posted on

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);
});
Enter fullscreen mode Exit fullscreen mode

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."
  });
Enter fullscreen mode Exit fullscreen mode

Methods in promises

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

Resolve 🚀

Returns a resolved Promise with the given value.

const resolvedPromise = Promise.resolve("Resolved!");
resolvedPromise.then(console.log); // "Resolved!"
Enter fullscreen mode Exit fullscreen mode

Reject 🚀

Returns a rejected Promise with the given error.

const rejectedPromise = Promise.reject("Rejected!");
rejectedPromise.catch(console.error); // "Rejected!"
Enter fullscreen mode Exit fullscreen mode

All 🚀

Waits for all Promises in an array to resolve. If one fails, the entire chain rejects.

const p1 = Promise.resolve(1);
const p2 = new Promise((resolve) => setTimeout(resolve, 1000, 2));
const p3 = Promise.reject("Error!");

Promise.all([p1, p2, p3])
  .then(console.log)
  .catch(console.error); // "Error!"
Enter fullscreen mode Exit fullscreen mode

allSettled 🚀

Waits for all Promises to settle (resolve or reject), returning an array with results.

Promise.allSettled([p1, p2, p3]).then(console.log);
/*
[
  { status: "fulfilled", value: 1 },
  { status: "fulfilled", value: 2 },
  { status: "rejected", reason: "Error!" }
]
*/
Enter fullscreen mode Exit fullscreen mode

race 🚀

Returns the first Promise that settles (either resolve or reject).

const fast = new Promise((resolve) => setTimeout(resolve, 500, "Fast!"));
const slow = new Promise((resolve) => setTimeout(resolve, 1000, "Slow!"));

Promise.race([fast, slow]).then(console.log); // "Fast!"
Enter fullscreen mode Exit fullscreen mode

any 🚀

Returns the first fulfilled Promise, ignoring rejections. Rejects only if all fail.

const fail1 = Promise.reject("Fail 1");
const fail2 = Promise.reject("Fail 2");
const success = new Promise((resolve) => setTimeout(resolve, 300, "Success!"));

Promise.any([fail1, fail2, success]).then(console.log).catch(console.error); // "Success!"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)