I have a cardsList that is an object got from a fetch().
I do a mapping on cardList and to each one I make a new request getting more information.
I got a really strange situation:
Map is synchronous, but it will first print 'Log2' and after 'Log1'.
After all, when I print cardsList I see all cardInfo object information, but if try to access it like cardsList[0].cardInfo I got undefined.
Do you know what is going on?
*Obs: I tried with await in fetchCardsInfo, but I got the same situation: I see the informations when I print but I cannot access it.
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
}
Promise.all is your friend
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With