admin管理员组

文章数量:1335832

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) 

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) 
Share Improve this question edited Jun 5, 2018 at 8:32 Taki 17.7k5 gold badges28 silver badges48 bronze badges asked May 1, 2018 at 15:45 Sona ShettySona Shetty 1,0474 gold badges20 silver badges41 bronze badges 1
  • No, it's not possible to run an asynchronous function synchronously. You can time the calls sequentially, though. Use a recursive approach. – Bergi Commented May 1, 2018 at 15:46
Add a ment  | 

1 Answer 1

Reset to default 5

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

本文标签: javascriptNodejs Synchronous for loopStack Overflow