javascript - 如何在带有参数的 promise 数组上使用 Promise.all()?

标签 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
});

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

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

最佳答案

改用 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)
});

关于javascript - 如何在带有参数的 promise 数组上使用 Promise.all()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49744707/

相关文章:

node.js - MongoDB 更改流与 socket.io

javascript - socket.emit 不适用于移动 chrome(但它适用于隐身模式)

javascript - array.map() 内的 Sails Waterline ORM 查询

Javascript, Promise.then 返回值

Javascript String.fromCharCode 返回错误值

javascript - 在表格行悬停时填充 svg 路径

javascript - 嵌套 ng-repeat $digest() 不会更新 View

javascript - 使用 .get(0) 或 .html() 返回带有 jQ​​uery 的 HTML

node.js - 如何在 Loopback 中返回随机对象?

javascript - Promise.then 绑定(bind)问题