简体   繁体   中英

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

I am facing some issues with Promise.all() . For example if finalArr has 2 objects, each line is running 2 times at a time. Its not running synchronously:

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

Resolving the provided promises in "parallel" is actually one of the advantages of Promise.all() if performance is of importance and you do not care about the order. If you need to resolve the promises sequentially, you can simply use a 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM