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
1 Answer
Reset to default 5you 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
版权声明:本文标题:javascript - Nodejs Synchronous for loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742367516a2461585.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论