有人可以帮助我以同步方式运行以下循环吗?由于下面的代码是异步执行的,arra
的值总是返回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)
答案 0 :(得分:3)
您可以尝试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) );