Sona Shetty
Sona Shetty

Reputation: 1047

Nodejs Synchronous for loop

Can some one help me to run the below loop in a synchronous manner? As the below code is getting executed asynchronously,value of arra is always returning null.

var arra=[];
//Query doctors collection and get necessary details           
for (i = 0; i <arr.length; i++) {
    var docregistrationnumber = arr[i].docregistrationnumber
    var registrationAuthority = arr[i].docregistrationauthority                
    doctorData.getDoctorByRegNumber(docregistrationnumber,registrationAuthority,function(data){
        console.log(JSON.stringify(data))  
        arra.push(data)                
    })
} 
console.log(arra) 

Upvotes: 1

Views: 10171

Answers (1)

Taki
Taki

Reputation: 17654

you can try async/await

var arra = [];
//Query doctors collection and get necessary details    

async function getData() {
  for (i = 0; i < arr.length; i++) {
    var docregistrationnumber = arr[i].docregistrationnumber
    var registrationAuthority = arr[i].docregistrationauthority
    var data = await doctorData.getDoctorByRegNumber(docregistrationnumber, registrationAuthority);

    arra.push(data);   
  }

  return arra;
}  

getData().then( data => console.log(data) );  

Upvotes: 5

Related Questions