【问题标题】:Promise must be async - Angular 9承诺必须是异步的 - Angular 9
【发布时间】:2021-02-04 11:15:10
【问题描述】:

我想单独上传一组文件,然后仅在文件完成后才发布其他数据。到目前为止,每个文件都有自己的请求上传,但我不能让其他请求等待文件完成上传 - 尽管有 async/await,但它们都同时执行。

这是我的代码的简化版本(其中run() 需要是可观察的或承诺,postOtherDatas() 需要等待 uploadFileList() 完成):

public async run(data: Data): Promise<Object> {
    await this.uploadFileList(data.files); // run this first
    return this.postOtherDatas(data.otherData).subscribe(); // run this only if uploadFileList() is done
}
    
public async uploadFileList(files: File[]) {
  return await Promise.all(files.map((file) => {
    this.uploadFile(file).subscribe();
  }));
}

public uploadFile(file: File): Observable<HttpEvent<any>> {
  const req = new HttpRequest('POST', `apiUrl/postfile`, 
    formData, { withCredentials: true });
  return this.http.request(req);
}
  
public postOtherDatas(formData: FormData) {
  return this.http.post('apiUrl/postotherdata',
    formData, { withCredentials: true }
  );
}

我也尝试过,但从未调用过 postOtherDatas()

public run(data: Data): Observable<Object> {
   return this.uploadFileList(data.files).then(() => this.postOtherDatas(data.otherData).subscribe())
}

【问题讨论】:

  • 我会使用 forkJoin 形式的 RxJs。你也可以.then a promiseAll 并在其中调用你喜欢的方法。此外,Promise.then 是 void,Observable.subscribeSubscription,而不是 Observable。

标签: angular typescript async-await observable es6-promise


【解决方案1】:

订阅 rxjs 不是承诺:

public async uploadFileList(files: File[]) {
  return await Promise.all(files.map((file) => {
    // Not a promise!
    this.uploadFile(file).subscribe();
  }));
}

如果你想继续使用 Promise,你可以这样做:

public async uploadFileList(files: File[]) {
  return await Promise.all(files.map((file) => {
    return this.uploadFile(file).toPromise();
  }));
}

您的run 方法中也需要这样做:

public async run(data: Data): Promise<Object> {
    await this.uploadFileList(data.files); // run this first
    return this.postOtherDatas(data.otherData).toPromise(); // run this only if uploadFileList() is done
}

但是:我建议你更谨慎地使用 rxjs,它有一些很棒的工具可以处理更复杂的异步性。例如。 Promise.all 可以使用forkJoin 函数来实现。

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多