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