简体   繁体   English

为什么 flatMap 不删除空数组?

[英]Why flatMap doesn't remove empty arrays?

I have a flatMap function that fetch and return data for each item in array.我有一个 flatMap 函数,它为数组中的每个项目获取和返回数据。 It also returns an empty array if item doesn't have certain informations.如果 item 没有某些信息,它也会返回一个空数组。 Since I'm using flatMap I was expecting that it will remove all the empty arrays, but the finished array still have them included.由于我使用的是 flatMap,我原以为它会删除所有空数组,但完成的数组仍然包含它们。

Function:功能:

 Promise.all(
        array.flatMap(async (item) => {
        const fetchedData = await fetch(`${item.url}`)
            .then(response => response.json())
            .then(data => data.stats.length ? data : null);
        return fetchedData ? { ...fetchedData } : [];
    })).then(data => console.log(data));

Also when I log the data using console.log(data.flat()) instead of console.log(data) all the empty arrays are removed, but it would require iterating through array one more time.此外,当我使用console.log(data.flat())而不是console.log(data) 记录数据时,所有空数组都被删除,但它需要再迭代一次数组。 Any ideas why flatMap isn't doing it by itself?为什么 flatMap 不自己做的任何想法?

It's because your callback inside of flatMap is an async function, so it always returns a Promise no matter what.这是因为你在flatMap内部的回调是一个async函数,所以无论如何它总是返回一个 Promise 。 Let's say array has two items, the first which will have fetched data and the second which will not, here's an example of what will happen:假设array有两个项目,第一个项目将获取数据,第二个项目不会,以下是将发生的情况的示例:

array is: [item1, item2] array是: [item1, item2]

After the map part of flatMap you get [Promise(pending), Promise(pending)] (note that the mapping is instantaneous, it doesn't wait for the async functions to complete, it just gets the promise returned from them).flatMap的 map 部分之后你会得到[Promise(pending), Promise(pending)] (注意映射是即时的,它不会等待异步函数完成,它只是从它们那里得到承诺返回)。

After the flattening part you get [Promise(pending), Promise(pending)] (note that this is the same as the above line - promises can't be flattened.).在展平部分之后,您会得到[Promise(pending), Promise(pending)] (注意,这与上面的行相同 - 承诺不能展平。)。

Promise.all.then() waits for each promise to resolve and passes the result as data which you log and is [someObject, emptyArray] . Promise.all.then() 等待每个承诺解决并将结果作为您记录的data传递,并且是[someObject, emptyArray]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM