skip to Main Content

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


  1. Your .map generates an array of Promises, not an actual Promise. This is because your mapping function is an async function, which, effectively, returns a Promise for each element of invoice.orders.

    To wait for all of those Promises to resolve, you need to use Promise.all.

    For example:

    await Promise.all(arrayOfPromises)
    
    Login or Signup to reply.
  2. You are pushing orders to an array that doesn’t exist because you spelled awaitingOrders wrong. It should say awaitingOrders.push(order);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search