0

如何创建这样的数组:

[foo(1,3), foo(5,7)]

在node.jsArray.map中放入一个函数?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
4

2 回答 2

0

您的示例只是缺少async增量函数中的关键字和返回语句。

添加async将返回一个承诺,而您的 foo.map 将返回一个承诺数组。

例如:

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 ]
于 2021-02-01T08:30:17.803 回答
0

如果要将函数存储在带有参数的数组中,可以使用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, 1, 2), foo.bind(null, 4, 2)]
undefined
> arr
[ [Function: bound foo], [Function: bound foo] ]
> arr.map(f => f());
[ 3, 6 ]
于 2021-02-01T09:59:19.120 回答