Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async calls in loop delayed

I have a function which makes two asynchronous calls to the database inside a loop. The issue is that the return function works before the data from the loop is retrieved.

const myFunc = async (customers) => {
  const customerList = customers.map(async (customer) => {
    const cashCollected = await knex('cash_collections')
      .sum('amount_collected as amount')
      .where('account_code', customer.code)
      .first();
    const orderValue = await knex('orders')
      .sum('discounted_price as amount')
      .where('customer_id', customer.id)
      .first();
    const customerData = {
      name: customer.name,
      outstandingBalance: (orderValue.amount - cashCollected.amount),
    };
    // This line works after console.log(customerList);
    console.log(customerData);
    return customerData;
  });
   // console and return works before data is retrieved 
   // (before console.log(customerData) is run)
  console.log(customerList);
  return customerList;
};

// Function is called in another place
myFunc()
like image 741
Muljayan Avatar asked Jun 21 '26 08:06

Muljayan


1 Answers

You're making all of those calls in parallel by doing them in the map callback. If you really want to do that, you need to wait for those calls to settle by using Promise.all:

const customerList = await Promise.all(customers.map(async (customer) => {
    // ...
}));

If you want to do them in series instead, use a for loop and await each response. :-) But it looks like parallel is okay.

like image 135
T.J. Crowder Avatar answered Jun 23 '26 21:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!