如何在承担参数的promises数组上使用Promise.all()?

Emm*_*N K 2 javascript node.js es6-promise

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
});
Run Code Online (Sandbox Code Playgroud)

如何编写Promise.all()函数从不同大小的数组中获取参数?

我想将参数传递给类.all()方法中接受的promise数组Promise.最好的方法是什么?

xia*_*glu 6

使用map替代

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)
});
Run Code Online (Sandbox Code Playgroud)