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/