任何人都可以使用 async await 帮助我。困住了请帮助我,用异步和等待很难理解。这是我的代码。我希望我的代码按顺序工作。变量 ids 也是数组,而 tmpDoc 也是数组文档,以便循环推送到数组,然后在用户插入 $ in 数组后删除了集合用于插入文档数组的rawCollection。请参阅我的代码推荐
let items = Inventories.find(
{
itemId: itemId,
tranDate: {
$gt: tranDate,
},
branchId: branchId,
warehouseId: warehouseId,
},
{
sort: {
tranDate: 1,
createdAt: 1,
// _id: 1,
},
}
).fetch()
try {
let ids = [],
tmpDoc = []
let tmpLastBalQty = balanceQty
let tmpLastBalAmount = balanceAmount
let tmpAvgCost = avgCost
_.forEach(items, async item => {
let condition = false
if (
item.refType === 'Cash_Sale' ||
item.refType === 'Invoice' ||
item.refType === 'Sale_Return' ||
item.refType === 'Receipt_Refund'
) {
item.cost = tmpAvgCost
condition = true
}
const balQty = _.round(tmpLastBalQty + item.qty, decimalNumber())
let balAmount = _.round(
tmpLastBalAmount + item.qty * item.cost,
decimalNumber()
)
let avgCost = _.round(balAmount / balQty, decimalNumber())
// Check balQty = 0
if (balQty === 0) {
balAmount = 0
avgCost = item.cost
}
if (!_.isFinite(avgCost)) {
avgCost = item.avgCost
}
let data = {
_id: item._id,
refType: item.refType,
refId: item.refId,
tranDate: item.tranDate,
itemId: item.itemId,
cost: condition ? avgCost : item.cost,
price: item.price,
qty: item.qty,
balanceQty: balQty,
avgCost: avgCost,
balanceAmount: balAmount,
warehouseId: item.warehouseId,
branchId: item.branchId,
}
//
ids.push(item._id)
tmpDoc.push(data)
//
tmpAvgCost = avgCost
tmpLastBalAmount = balAmount
tmpLastBalQty = balQty
})
Inventories.remove({ _id: { $in: ids } })
await Inventories.rawCollection().insertMany(tmpDoc)
return 'success'
} catch (error) {
console.log(error)
throwError(error)
}
答案 0 :(得分:0)
您不能使用forEach
。只需使用for
循环,它将按您期望的方式工作。
请参见下面的示例代码:
myFunction = async items => {
let data = [];
for (let i = 0; i < items.length; i++) {
await fetchItems(items[i]).then(response => {
data.push(response)
});
}
return data;
};