Trying to update tatol and orders value but it isn’t updating please help.
let total = 0;
let awaitingOrders = [];
invoice.orders.map(async(order, i) =>{
await db.collection("orders")
.doc(order.id).get().then(orderDoc => {
total += orderDoc.data().total;
awaitingOrder.push(order);
}
}).catch((error) => {
console.log(error);
});
console.log(total, awaitingOrders);
Total shows 0 and orders empty[] on console.log(). Why?
2
Answers
Your
.map
generates an array of Promises, not an actual Promise. This is because your mapping function is anasync
function, which, effectively, returns a Promise for each element ofinvoice.orders
.To wait for all of those Promises to resolve, you need to use
Promise.all
.For example:
You are pushing orders to an array that doesn’t exist because you spelled
awaitingOrders
wrong. It should sayawaitingOrders.push(order);