panzerdp / dmitripavlutin.com-comments

7 stars 0 forks source link

promise-all/ #130

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

How to Use Promise.all()

How to use Promise.all() to perform parallel async operations.

https://dmitripavlutin.com/promise-all/

Barto-dev commented 3 years ago
async function myPromiseAll (arr) {
  const resultArr = [];
  for (let i = 0; i < arr.length; i ++) {
    try {
      const data = await arr[i];
      resultArr.push(data);
    } catch (e) {
      return e;
    }
  }
  return resultArr;
}

Delete plz previously comment:)

panzerdp commented 3 years ago
async function myPromiseAll (arr) {
  const resultArr = [];
  for (let i = 0; i < arr.length; i ++) {
    try {
      const data = await arr[i];
      resultArr.push(data);
    } catch (e) {
      return e;
    }
  }
  return resultArr;
}

Delete plz previously comment:)

Thanks for sharing your solution @Barto-dev. But it doesn't work well when one of the promises rejects: in such case the promise returned by myPromiseAll() should reject too.

Barto-dev commented 3 years ago
async function myPromiseAll (arr) {
  const resultArr = [];
  for (let i = 0; i < arr.length; i ++) {
    try {
      const data = await arr[i];
      resultArr.push(data);
    } catch (e) {
      throw e;
    }
  }
  return resultArr;
}

Now its return error if promise reject:)

ki9us commented 2 years ago

Isn't there a javascript syntax to store array elements as variables? Something like:

let [var1, var2] = [2, 4]

I've been doing this with my Promise.all() returns and feel like it could be shorter:

let result = Promise.all([...])
let var1 = result[0]
let var2 = result[1]
chadidi02 commented 2 years ago

console.log("Hello World");

const products = async () => { try { let item1 = fetch("https://fakestoreapi.com/products/1").then(resp => resp.json()); let item2 = fetch('https://fakestoreapi.com/products/2').then(resp => resp.json()); let item3 = fetch('https://fakestoreapi.com/products/3').then(resp => resp.json()); let item4 = fetch("https://fakestoreapi.com/products/4").then(resp => resp.json()); let item5 = fetch('https://fakestoreapi.com/products/5').then(resp => resp.json()); let item6 = fetch('https://fakestoreapi.com/products/6').then(resp => resp.json()); const item7 = fetch("https://api.github.com/users/joshuabarber").then(resp => resp.json());

    const requests = ([item1, item2, item3, item4, item5, item6, item7]
        .map(p => p.then(data => data))
    );

    await Promise.all(requests)

    console.log(requests);

} catch (error) {
    console.log(error);
}

} products()

minemax-ua commented 2 years ago

Horstmann in his book claims that "The Promise.all does not actually run tasks in parallel. All tasks are executed sequentially in a single thread." Is he wrong? 😮

alex-golovanov commented 2 years ago
async function myPromiseAll (arr) {
  const resultArr = [];
  for (let i = 0; i < arr.length; i ++) {
    try {
      const data = await arr[i];
      resultArr.push(data);
    } catch (e) {
      throw e;
    }
  }
  return resultArr;
}

@Barto-dev this code will execute promises in sequence, one after another. Promise.all runs them all at the same time, in parallel.

So it should look more like this:

function promiseAll(promises){
  return new Promise((resolve, reject) => {
    let count = 1;
    const result = [];
    for (let i = 0; i < promises.length; i++) {
      const promise = promises[i];
      promise
        .then((res) => {
          result[i] = res;
          if (count === promises.length) {
            resolve(result);
          }

          count++;
        })
        .catch((e) => {
          reject(e);
        });
    }
  });
}
Baharak12 commented 2 years ago

Hi there, a question for you! How we can stop/cancel a promise before fetching the promise itself?