1

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) 
1
  • No, it's not possible to run an asynchronous function synchronously. You can time the calls sequentially, though. Use a recursive approach. Commented May 1, 2018 at 15:46

1 Answer 1

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) );  
Sign up to request clarification or add additional context in comments.

2 Comments

Which npm package shud i install to work with async/await library
It's not a library, it's a language feature. You need to use Node 7.6 or newer. getDoctorByRegNumber also must return a Promise for this to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.