问题描述
如何创建这样的数组:
[foo(1,3),foo(5,7)]
使用 Array.map
放入 node.js 中的 Promise.all
函数?
示例:
const foo = [1,2,3]
function increment(n) {
console.log(n + 1)
}
Promise.all(
foo.map(n => {
return increment(n)
})
)
预期输出:
2
3
4
解决方法
您的示例只是在 increment 函数和 return 语句中缺少 async
关键字。
添加 async
将返回一个 promise,而您的 foo.map 将返回一个 promise 数组。
例如:
const foo = [1,2,3]
async function increment(n) {
return n + 1;
}
const arrayOfPromises = foo.map(n => {
return increment(n);
})
console.log("arrayOfPromises",arrayOfPromises)
Promise.all(arrayOfPromises).then((values) => {
console.log(values);
});
输出:
arrayOfPromises [ Promise { 2 },Promise { 3 },Promise { 4 } ]
[ 2,3,4 ]
,
如果要将函数存储在带参数的数组中,可以使用 bind。
function foo(a,b) {
return a + b;
}
const arr = [foo.bind(null,1,2),foo.bind(null,4,2)]
const result = arr.map(f => f());
// result should be [3,6]
使用 REPL 进行演示:
> function foo(a,b) { return a+b; }
undefined
> foo(1,2)
3
> const arr = [foo.bind(null,2)]
undefined
> arr
[ [Function: bound foo],[Function: bound foo] ]
> arr.map(f => f());
[ 3,6 ]