【问题标题】:How to call method after getting response from previously called method从先前调用的方法获得响应后如何调用方法
【发布时间】:2019-06-04 22:25:21
【问题描述】:

我正在尝试将文件数组保存到 Spring Boot 服务器。一次保存一个文件。我正在使用 for 循环迭代文件数组并请求保存每个文件。在这里,我希望仅在获得第一个文件的响应后才进行下一次调用。我已经尝试了下面给出的代码,但我无法实现它。

组件.ts

public uploadNewsFiles() {

for (let index = 0; index < this.files.length; index++) {
  debugger;
  var body = new FormData();
 // alert(this.files[index].name);
  body.append('file', this.files[index]);
  this.uploading.push(true);
  this.uload(body,this.newsId,this.getFileDescriptionFormGroup(index)
  .controls['des'].value,index).then((status:any)=>
  {
    if (status.status === 'success') {
    //  alert('success');
      body.delete('file');
      this.uploading[index] = false;
      this.uploadingStatus.push(true);
     
    } else {
      body.delete('file');
      this.uploading[index] = false;
      this.uploadingStatus.push(false);
    }
  },(err)=>alert('failed'))
  }

   // body.append('newsId',this.newsId);
   }

  async uload(body,newsId,desc,index) {
  return await this.service.saveFiles(body, newsId,desc).toPromise();
  }

service.ts

public saveFiles(body,newsId,des) {

return this.http.post(this.url + '/saveFiles? 
newsId='+newsId+'&fileDescription='+des,body);
}

【问题讨论】:

    标签: angular asynchronous async-await angular6


    【解决方案1】:

    由于您使用的是 Angular,我们可以利用 rxjs 库而不是使用 toPromise 并从 http 调用中链接 observables,例如:

    function modUploadFiles() {
      this.files
        .map((file, index) => {
          const body = new FormData();
          body.append("file", file);
    
          const newsId = this.newsId;
    
          const desc = this.getFileDescriptionFormGroup(index).controls["des"]
            .value;
    
          return this.service.saveFiles(body, newsId, desc).finally(status => {
            body.delete("file");
            this.uploading[index] = false;
            this.uploadingStatus.push(status.status === "success");
          })
        })
        .reduce((acc, next) => acc.flatMap(() => next))
        .subscribe(result => {/*Do something*/});
    }
    

    您可以在以下问题中查看更多信息:

    Chaining Observables in RxJS

    【讨论】:

      【解决方案2】:

      你可以使用asyncawait

      async uploadNewsFiles() {
      
      for (let index = 0; index < this.files.length; index++) {
        var body = new FormData();
        body.append('file', this.files[index]);
        this.uploading.push(true);
        await this.uload(body,this.newsId,this.getFileDescriptionFormGroup(index)
        .controls['des'].value,index).then((status:any)=>
        {
           if (status.status === 'success') {
             body.delete('file');
             this.uploading[index] = false;
             this.uploadingStatus.push(true);
      // here we are calling the 
           } else {
             body.delete('file');
             this.uploading[index] = false;
             this.uploadingStatus.push(false);
           }
          },(err)=>alert('failed'))
        }
      }
      
      uload(body,newsId,desc,index) {
        return new Promise((resolve, reject) => {
           this.service.saveFiles(body, newsId,desc).toPromise().then(resp => {
              resolve(resp); // here we are resolving our promise
           });
        });
      }
      
      

      服务

      public saveFiles(body,newsId,des) {
       return this.http.post(this.url + '/saveFiles? 
               newsId='+newsId+'&fileDescription='+des,body);
      }
      

      希望对你有帮助。

      【讨论】:

      • 如果你使用 await 你不应该使用 .then() 它已经返回响应。
      • 但是在这种情况下,我们有 api 调用,所以在使用 api 之后,我们解决了这个承诺,这不是正确的方法吗?我们应该写resolve而不写'then()'吗?
      猜你喜欢
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 2019-08-16
      • 2023-04-08
      相关资源
      最近更新 更多