【发布时间】:2019-11-04 11:12:40
【问题描述】:
我有一个函数,它在一个循环内对数据库进行两次异步调用。问题是返回函数在从循环中检索数据之前起作用。
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()
【问题讨论】:
-
因此,我们不会将部分答案折叠到问题中。我们将它们分开。编码愉快!
标签: javascript database async-await knex.js