如何在 javascript 中同步使用 promises for map 函数到 运行?

How to use promises for map function to run synchronously in javascript?

我在使用 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)
   }

如果性能很重要并且您不关心顺序,那么解决 "parallel" 中提供的承诺实际上是 Promise.all() 的优势之一。如果您需要按顺序解决承诺,您可以简单地使用 for .. of-loop:

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);
}