【问题标题】:How to use async and await in Angular to wait for a function to finish before executing the remainder of the function?如何在 Angular 中使用 async 和 await 来等待函数完成,然后再执行函数的其余部分?
【发布时间】:2021-08-31 01:58:18
【问题描述】:

我正在尝试在将记录保存到数据库之前上传图像。我需要在保存记录之前完成上传:

负责图片上传的函数:

  async uploadTrainingModule(selectedFiles: any = this.files) {
    // Perform Image Upload
    for (let i = 0; i < selectedFiles.length; i++) {
      await this.filesUploaded.push(selectedFiles[i]);
    }
  }

在上面的方法中使用了async和await,我希望在下面的方法中执行其他任何事情之前让该方法完成(这是负责写入DB的方法):

 createTrainingModule() {
    this.uploadTrainingModule().then(resp => {
        // Upload to DB code below
    })
  }

我的目标是仅在 uploadTrainingModule 方法完全完成后才执行注释下方的代码,但是,我上面所做的不起作用?我可以采取什么方法?

【问题讨论】:

    标签: angular typescript asynchronous async-await rxjs


    【解决方案1】:

    您可以通过以下步骤使用RxJS 函数来实现:

    • 使用forkJoin将所有上传函数与一个Observable结合起来,并从uploadTrainingModule返回。
    • subscribe 到你的createTrainingModule 中的这个Observable,并在subscribe 方法中做你需要的事情。

    您的代码应如下所示:

    import { forkJoin, from, Observable } from "rxjs";
    
    uploadTrainingModule(selectedFiles: any = this.files): Observable<any> {
      // Perform Image Upload
      // `forkJoin` will return one Observable once all the inner Observables (generated from promises using RxJS's `from` function) have been completed
      return forkJoin(
        selectedFiles.map((file) => from(this.filesUploaded.push(file)))
      );
    }
    
    createTrainingModule() {
      this.uploadTrainingModule().subscribe((resp) => {
        // Upload to DB code below
      });
    }
    

    【讨论】:

    • 根据上述建议,只能上传一张图片(一次可以上传多张),结果我收到以下错误:“ERROR TypeError: You provide '1' where a流是预期的。您可以提供 Observable、Promise、Array 或 Iterable。”,这可能是什么原因?
    • 请问this.filesUploaded.push这个方法的返回类型是什么?
    • this.filesUploaded 是一个文件数组 - 即一个 FileList,每次在 for 循环中循环时,它都会添加另一个文件。
    • 那么,将file 推送到数组的async 进程在哪里?真正的上传请求何时发生?
    • 最初选择文件,然后将这些文件推送到 FileList 数组。然后用户点击上传按钮,调用“createTrainingModule”方法。由于调用了“createTrainingModule”,FileList 数组“filesUploaded”填充了初始 FileList 数组中的文件(在选择文件时)。现在填充了数组“filesUploaded”,我在数组中每个文件的子组件的选择器上运行 ngfor(该子组件是保存上传文件的实际方法的组件)。
    猜你喜欢
    • 2011-02-12
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多