Science Knowings: JavaScript Course For Social Media

Promise.all() Method

Promises: A Deep Dive

Previously, we explored the Object.values() method, which allows us to obtain an array of a given object's own enumerable property values. Now, we embark on a journey into asynchronous JavaScript and the powerful Promise object.

Introduction to Promises

What are Promises?

Promises represent the eventual completion or failure of an asynchronous operation. They provide a mechanism to handle asynchronous code in a more structured and maintainable way.

Promise Lifecycle

A promise goes through three distinct states:
1. Pending: Initial state, operation is in progress.
2. Fulfilled: Operation completed successfully, with a result (resolved)
3. Rejected: Operation failed, with a reason (rejected)

Creating Promises

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise resolved!');
  }, 2000);
});

This creates a promise that will be resolved after 2 seconds with the message 'Promise resolved!'

Consuming Promises

promise.then((result) => {
  console.log(result);
}).catch((error) => {
  console.error(error);
}).finally(() => {
  console.log('Promise completed!');
});

This consumes the promise, logging the result if fulfilled, error if rejected, and a completion message regardless.

Promise Chaining

promise1.then(result1 => {
  return promise2(result1);
}).then(result2 => {
  return promise3(result2);
}).then(result3 => {
  console.log(result3);
}).catch((error) => {
  console.error(error);
});

Promises can be chained to handle a sequence of asynchronous operations.

Benefits of Promises

  • Improved code readability and maintainability
  • Error handling and recovery
  • Asynchronous operations without callback hell

Promise.all() Method

The Promise.all() method takes an array of promises as its argument and returns a new promise.
This new promise resolves when all the input promises have been resolved or if any of the input promises reject, in which case the returned promise rejects with the reason of the first rejected promise.

Syntax of Promise.all()

Promise.all([promise1, promise2, ...]).then((results) => {
  console.log(results);
}).catch((error) => {
  console.error(error);
});

Use Cases of Promise.all()

  • Loading multiple resources (e.g., images, scripts)
  • Performing multiple API calls
  • Validating multiple user inputs

Advantages of Promise.all()

  • Handles multiple promises simultaneously
  • Simplifies error handling
  • Improves code organization and readability

Next: Promise.race() Method

In the next session, we'll explore the Promise.race() method, which is useful for scenarios where we want to wait for the first promise to resolve or reject, regardless of the state of other promises in the array.
Follow us for more JavaScript deep dives!