자바 스크립트에서 동기식으로 실행되는 맵 함수에 대한 약속을 사용하는 방법은 무엇입니까?

차루

에 몇 가지 문제가 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프로 미스를 순차적으로 해결해야하는 경우 간단히 -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);
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관