【发布时间】: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。你也可以.thenapromiseAll并在其中调用你喜欢的方法。此外,Promise.then是 void,Observable.subscribe是Subscription,而不是 Observable。
标签: angular typescript async-await observable es6-promise