How to wait for response inside for loop?

谁说我不能喝 提交于 2019-12-14 03:35:49

问题


Description : I called an HTTP request inside for loop.I want to get the response from service file then increase loop.How can i wait to get response from service file then execute loop.

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

Please advise


回答1:


You should use an async function. First convert the HTTP request to a promise, then call that promise asynchronously inside the for loop:

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


来源:https://stackoverflow.com/questions/54861978/how-to-wait-for-response-inside-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!