JavaScript Promises

***

Discover how to master JavaScript Promises and streamline your asynchronous programming. Our guide provides practical examples and clear explanations to enhance your coding skills.

Promises, async, and await are core features of JavaScript used for asynchronous programming, but they are not considered methods of built-in objects like String, Array, Object, etc. Instead, they are part of the language's syntax and API. Below, I will include a section for Promises and async/await to provide a comprehensive overview.

Asynchronous Programming in JavaScript

Promises

Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value.

Creating a Promise

let promise = new Promise((resolve, reject) => {
  // asynchronous operation
  let success = true;
  if (success) {
    resolve("Operation was successful");
  } else {
    reject("Operation failed");
  }
});

Using Promises

promise
  .then(result => {
    console.log(result); // "Operation was successful"
  })
  .catch(error => {
    console.error(error); // "Operation failed"
  });

Promise Methods

Promise.all()

Waits for all promises to be resolved or any to be rejected.

let p1 = Promise.resolve(3);
let p2 = 42;
let p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});
 
Promise.all([p1, p2, p3]).then(values => {
  console.log(values); // [3, 42, "foo"]
});

Promise.allSettled() (ES2020)

Waits for all promises to be settled (either resolved or rejected).

let p1 = Promise.resolve(3);
let p2 = Promise.reject("error");
let p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});
 
Promise.allSettled([p1, p2, p3]).then(results => {
  console.log(results);
  // [{status: "fulfilled", value: 3}, {status: "rejected", reason: "error"}, {status: "fulfilled", value: "foo"}]
});

Promise.any() (ES2021)

Waits for any promise to be resolved or all to be rejected.

let p1 = Promise.reject(0);
let p2 = Promise.resolve(42);
let p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});
 
Promise.any([p1, p2, p3]).then(value => {
  console.log(value); // 42
});

Promise.race()

Waits for the first promise to be resolved or rejected.

let p1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one');
});
let p2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two');
});
 
Promise.race([p1, p2]).then(value => {
  console.log(value); // "two"
});

Promise.resolve()

Returns a promise that is resolved with the given value.

Promise.resolve('Success').then(value => {
  console.log(value); // "Success"
});

Promise.reject()

Returns a promise that is rejected with the given reason.

Promise.reject(new Error('fail')).catch(error => {
  console.error(error); // Error: fail
});

async and await

async and await provide a simpler way to work with asynchronous code, avoiding the need to explicitly use then and catch.

async Function

An async function returns a promise.

async function fetchData() {
  return "Data fetched";
}
fetchData().then(result => console.log(result)); // "Data fetched"

await Keyword

await pauses the execution of the async function and waits for the promise to resolve or reject.

async function fetchData() {
  let data = await new Promise((resolve, reject) => {
    setTimeout(() => resolve("Data fetched"), 1000);
  });
  console.log(data); // "Data fetched"
}
fetchData();

Error Handling with async/await

Use try/catch to handle errors in async functions.

async function fetchData() {
  try {
    let data = await new Promise((resolve, reject) => {
      setTimeout(() => reject("Error fetching data"), 1000);
    });
    console.log(data);
  } catch (error) {
    console.error(error); // "Error fetching data"
  }
}
fetchData();

Combining Promises and async/await

You can combine async/await with other Promise methods for more complex scenarios.

async function fetchMultipleData() {
  try {
    let [result1, result2, result3] = await Promise.all([
      Promise.resolve("Result 1"),
      Promise.resolve("Result 2"),
      new Promise((resolve, reject) => setTimeout(resolve, 1000, "Result 3"))
    ]);
    console.log(result1, result2, result3); // "Result 1", "Result 2", "Result 3"
  } catch (error) {
    console.error(error);
  }
}
fetchMultipleData();

This comprehensive overview includes the usage and methods related to Promises and async/await, providing a solid foundation for handling asynchronous operations in JavaScript.