我在使用 Promise.all()
. 例如,如果finalArr有2个对象,每一行同时运行2次。它不是同步运行的。
try{
let newData = await Promise.all(finalArr.map(async receiveData => {
receiveData['internalCode'] = await RecievedLots.beforeRLCreation(receiveData.company_id)
console.log(receiveData.internalCode)
// For Example above console line is printing 2 times if finalArr has 2 objects
// same like remaining functions.. how to avoid this?
const createdReceiveMaterial = await RecievedLots.create(receiveData).fetch();
if(!!createdReceiveMaterial && Object.keys(createdReceiveMaterial).length > 0) {
const poMaterial = await POMaterials.findOne({id: receiveData.po_material_id});
let status_id = poMaterial.status_id;
let quantityReceived = poMaterial.qty_received + receiveData.qty_recieved
let qtyAvailable = poMaterial.qty_available+ receiveData.qty_recieved;
if(poMaterial.quantity <= quantityReceived){
status_id = 6
}
else if(poMaterial.quantity > quantityReceived && quantityReceived != 0 ){
status_id = 5
}
else if(quantityReceived == 0){
status_id = 4
}
const updatePOmaterial = await POMaterials.update({id: receiveData.po_material_id})
.set({qty_received:quantityReceived,status_id:status_id, qty_available: qtyAvailable}).fetch()
// console.log(updatePOmaterial)
}
return receiveData
}))
cb(null, newData)
}
catch(err){
cd(err)
}
以 "并行 "的方式解决所提供的承诺,这实际上是 Promise.all()
如果性能很重要,而你并不关心顺序。如果你需要按顺序解决承诺,你可以简单地使用一个 for .. of
-循环。
const newData = [];
for (const receiveData of finalArr) {
receiveData['internalCode'] = await RecievedLots.beforeRLCreation(receiveData.company_id);
// rest of your code here
// ...
// at the end simply push to newData instead of returning receive Data
newData.push(receiveData);
}