javascript - Nodejs Synchronous for loop - Stack Overflow

Can some one help me to run the below loop in a synchronous manner? As the below code is getting execut

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742367516a4430610.html

相关推荐

  • javascript - Nodejs Synchronous for loop - Stack Overflow

    Can some one help me to run the below loop in a synchronous manner? As the below code is getting execut

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信