创建一个包含多个函数的数组

Create an array with multiple functions in it

如何创建这样的数组:

[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

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

添加 async 将 return 一个承诺,而您的 foo.map 将 return 一系列承诺。

例如:

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, 1, 2), foo.bind(null, 4, 2)]
undefined
> arr
[ [Function: bound foo], [Function: bound foo] ]
> arr.map(f => f());
[ 3, 6 ]