Search code examples
javascriptnode.jses6-promise

How to use Promise.all() on array of promises which take parameters?


let locArr = [{ x: 0, y: 0 }, { x: 2, y: 4 }, { x: 6, y: 8 }];

// my asynchronous function that returns a promise
function findLoc(x, y) {
    return new Promise((resolve, reject) => {
        let a = setTimeout(() => {
            resolve({ x: x * x, y: y * y });
        }, 500);
    });
}

Promise.all([
    // my problem is below
    findLoc(locArr[0].x, locArr[0].y),
    findLoc(locArr[1].x, locArr[1].y),
    findLoc(locArr[2].x, locArr[2].y),
]).then(values => {
    // all values from all the promises
});

How can I write the Promise.all() function to take parameters from an array of varying size?

I want to pass arguments to the array of promises accepted in the .all() method of the Promise class. What is the best way to do that?


Solution

  • use map instead

    let locArr = [{
      x: 0,
      y: 0
    }, {
      x: 2,
      y: 4
    }, {
      x: 6,
      y: 8
    }];
    
    // my asynchronous function that returns a promise
    function findLoc(x, y) {
      return new Promise((resolve, reject) => {
        let a = setTimeout(() => {
          resolve({
            x: x * x,
            y: y * y
          });
        }, 500);
      });
    }
    
    Promise.all(
      locArr.map(o => findLoc(o.x, o.y))
    ).then(values => {
      // all values from all the promises
      console.log(values)
    });