Luc*_*eca 2 javascript react-native
我有一个cardsList从 a 得到的对象fetch()。我在 cardList 上做一个映射,并对每一个我提出一个新的请求以获取更多信息。我遇到了一个非常奇怪的情况:Map 是同步的,但它会先打印“Log2”,然后再打印“Log1”。
毕竟,当我打印时,cardsList我会看到所有cardInfo对象信息,但是如果尝试像cardsList[0].cardInfo未定义一样访问它。
你知道发生了什么吗?
* Obs:我尝试使用 await in fetchCardsInfo,但我遇到了同样的情况:我在打印时看到了信息,但无法访问它。
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
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)