javascript - 循环中的异步调用延迟

标签 javascript database async-await knex.js

我有一个函数可以在一个循环中对数据库进行两次异步调用。问题是返回函数在从循环中检索数据之前起作用。

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()

最佳答案

您可以通过在 map 回调中执行所有这些调用来并行进行这些调用。如果您真的想这样做,您需要使用 Promise.all 等待这些调用完成:

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

如果您想连续执行它们,请使用 for 循环并等待每个响应。 :-) 但看起来并行没问题。

关于javascript - 循环中的异步调用延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58692254/

相关文章:

java - 如何将主键的 Id 填充到外键

mysql - 是我在 3NF 中的下表。即使我有如下重复,我如何保持 3NF?

C# 异步/等待 I/O 绑定(bind)与 CPU 绑定(bind)操作

rust - 如何等待需要回调的函数?

python - 如何启动协程并继续执行同步任务?

javascript - 请帮助我完成这个简单的脚本

当for循环结束时Javascript执行一个 Action

database - 显示少一条数据库记录的表格工具

JavaScript 碰撞检测错误

javascript - MSXML : Javascript is not a scripting language