在 object.map() 中使用 Fetch,在 map 完成后返回结果。

4

我有一个cardsList对象,是从fetch()获取的。 我对cardList进行映射,并对每个映射项进行新的请求以获取更多信息。 我遇到了一个非常奇怪的情况: 映射是同步的,但它会先打印“Log2”,然后才是“Log1”。

最终,当我打印cardsList时,我可以看到所有cardInfo对象的信息,但如果尝试像cardsList[0].cardInfo这样访问它,我会得到undefined。

你知道发生了什么吗?

*注:我在fetchCardsInfo中尝试使用await,但我得到了相同的情况:我可以看到信息时打印,但我无法访问它。

buscarCartoes = async () => {
    let cardsList = await CodeConnectRequests.fetchCardsList()

    cardsList.map((card) => {
        const cardInfo = CodeConnectRequests.fetchCardsInfo(card.cartao.tkCartao)
        cardInfo.then(data=>{
            console.log('Log1')
            card['cardInfo'] = data                   
        })

        return card
    })

    console.log('Log2')
    console.log(cardsList)// Here I can see cardInfo infs
    console.log(cardsList[0].cardInfo)// But hete cardInfo will be undefined
}

1
.map() 返回一个新的数组(并且不改变原数组)。 - user5734311
同时,您正在试图在 .then() 回调内构建数组元素,这没有意义。您应该使用 await 等待 fetchCardsInfo() 请求并以此构建数组。 - Pointy
我认为fetchCardsInfo是异步函数,这就是为什么Log2先打印,然后才是Log1。你能否分享一下console.log(cardsList)的输出结果? - Prasun
1个回答

9

Promise.all 是您的好朋友。

buscarCartoes = async () => {
    let cardsList = await CodeConnectRequests.fetchCardsList()

    // wait for nested requests to fulfill
    await Promise.all(cardsList.map(async (card) => { // Notice callback is async
        card.cardInfo = await CodeConnectRequests.fetchCardsInfo(card.cartao.tkCartao)
        return card
    })

    console.log('Log2')
    console.log(cardsList)// Here I can see cardInfo infs
    console.log(cardsList[0].cardInfo)// But hete cardInfo will be undefined
}

工作得很好!谢谢!在你的评论之前,我找到了一个解决方案,但我知道它不是最好的:cardsList.map((card, index) => { const cardInfo = CodeConnectRequests.fetchCardsInfo(card.cartao.tkCartao) cardInfo.then(data => { card['cardInfo'] = data if (index == cardsList.length - 1) { this.props.setCardsList(cardsList) this.props.changeScreen(2) } }) return card }) - Lucas Mendes Mota Da Fonseca
1
@LucasMendesMotaDaFonseca 很高兴能够帮助到你。 - Yury Tarabanko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接