<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td class="border"></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
如何编写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()
类的.all()
方法中接受的promise数组。最好的方法是什么?
答案 0 :(得分:5)
使用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)
});
答案 1 :(得分:2)
您可以使用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(//map location to promise
location=>findLoc(location.x,location.y)
)
).then(values => {
// all values from all the promises
});
答案 2 :(得分:2)
这是一个需要稍微修改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(findLoc)).then(values => {
console.log(values);
});
的输入的技巧:
var someArray = [1,0,1,1,1,1,0,0,1,0,1,0,0,1,0,1,0,1,1,1,1,0,1,1,0,1,0];
function simpleForLoop(array){
var numArgs = someArray.length;
for(var loop = 0; loop < numArgs; loop++){
var arg = someArray[loop];
if(arg !== 0 && arg !== 1){ return false; }
}
return true;
}
var isbool = simpleForLoop(someArray);
答案 3 :(得分:0)
使用map,就像其他人说的那样,但也调整findLoc()
函数以获得最简单的读数:
let locArr = [{ x: 0, y: 0 }, { x: 2, y: 4 }, { x: 6, y: 8 }];
// my asynchronous function that returns a promise
function findLoc(coordinates) {
return new Promise((resolve, reject) => {
let a = setTimeout(() => {
resolve({
x: coordinates.x * coordinates.x,
y: coordinates.y * coordinates.y
});
}, 500);
});
}
Promise
.all(locArr.map(findLoc))
.then(values => {
console.log(JSON.stringify(values, false, 2));
});