max*_*tSO 6 javascript typescript flatmap
我想了解为什么使用.flatMap()withasync不会返回展平数组。
例如,对于 Typescript,这会返回一个数字数组:
我知道,对于简单的数字数组来说是没有用的,它只是更容易Promisse.all复制async
const numbers = [[1], [2], [3]];
// typed as number[]
const numbersFlatten = await Promise.all(
numbers.flatMap((number) => number),
);
Run Code Online (Sandbox Code Playgroud)
对于 Typescript,当这返回一个数字数组的数组时(刚刚添加了一个异步):
const numbers = [[1], [2], [3]];
// typed as number[][]
const numbersFlatten = await Promise.all(
numbers.flatMap(async (number) => number),
);
Run Code Online (Sandbox Code Playgroud)
Nic*_*ons 11
所有async函数都隐式返回 Promise。通过进行.flatMap()回调async,它现在返回一个解析为number数组中的 Promise。为了.flatMap()正确工作并使其结果扁平化,回调应该返回一个数组,而不是 Promise。以下是有问题的行为的示例:
const numbers = [[1], [2], [3]];
const promiseAllArg = numbers.flatMap(async (number) => number); // same as `.flatMap(number => Promise.resolve(number))`, flatMap doesn't know how to flatten `Promise<number>` into a resulting array
console.log(promiseAllArg); // [Promise<[1]>, Promise<[2]>, Promise<[3]>]Run Code Online (Sandbox Code Playgroud)
相反,您可以使用常规.map()调用来获取解析值的嵌套数组,然后.flat()调用:
(async () => {
const numbers = [[1], [2], [3]];
const awaitedNumbers = await Promise.all(
numbers.map(async (number) => number) // some async code
);
const numbersFlattened = awaitedNumbers.flat() // flatten the resolved values
console.log(numbersFlattened);
})();Run Code Online (Sandbox Code Playgroud)