Promise.all() - 04

Promise.all():

If we want to handle more than one promise at a time, then we can use the syntax Promise.all(); Here, we have to pass the promise as an array, and the array will take the promises as an array item. Now we can access each of the promises by chaining.

const fetchDataOne = fetch("https://jsonplaceholder.typicode.com/todos/1");
    const fetchDataTwo = fetch("https://jsonplaceholder.typicode.com/todos/2");

    Promise.all([fetchDataOne, fetchDataTwo])
      .then((values) => {
        return Promise.all(values.map((r) => r.json()));
      })
      .then(([value1, value2]) => {
        console.log(value1.title);
        console.log(value2.title);
      });

    // Or, we can use map() method here...
    // .then((values) => {
    //   values.map((item) => console.log(item.title));
    // });

    const promiseOne = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (true) {
            console.log("Promise 1 resolved");
          } else {
            console.log("Promise 1 failed");
          }
        }, 3000);
      });
    };   

 const promiseTwo = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (true) {
            console.log("Promise 2 resolved");
          } else {
            console.log("Promise 2 failed");
          }
        }, 5000);
      });
    };

    promiseOne();
    promiseTwo();

    Promise.all([promiseOne, promiseTwo])
      .then((result) => {
        console.log(result);
      })
      .catch((error) => {
        console.log(error);
      });



Post a Comment

Previous Post Next Post