描述:我在循环中拨打了http请求。我想从服务文件中获取响应,然后增加循环。我可以等待从服务文件然后执行循环。
for(let i=0;i<final_arr.length;i++)
{
this.user.list_upload(JSON.stringify(ins_arr)).subscribe(data=>{
if(data.hasOwnProperty('STATUS'))
{ if(data.STATUS.toLowerCase()=='success')
{
this.update();
}
else if(data.STATUS.toLowerCase() == 'error')
{
this.user.showToast(data.MESSAGE);
}
}
},err=>{
this.user.showToast("Error occurred in service file");
});
}
请建议
您应该使用异步函数。首先将http请求转换为承诺,然后在for循环内部调用该诺言异步:
asyncReq (){
return new Promise((resolve, reject) => {
this.user.list_upload(JSON.stringify(ins_arr)).subscribe(data=>{
if(data.hasOwnProperty('STATUS')){
if(data.STATUS.toLowerCase()=='success')
{
this.update();
resolve();
}
else if(data.STATUS.toLowerCase() == 'error')
{
this.user.showToast(data.MESSAGE);
reject();
}
}
},err=>{
this.user.showToast("Error occurred in service file");
reject(err);
});
})
}
//Async function where loop progresses only after asyncReq completes
async asyncForFunction () {
for(let i=0; i < final_arr.length; i++){
await this.asyncReq ();
}
}