我在试着拒绝。的异步API调用,并希望在Promise.all中处理所有返回和解析。
if(this.selectedDomains.length > 0) {
for(let i=0; i<this.selectedDomains.length; i++){
promises.push(
this.policyService.exportPolicies(this.selectedDomains[i].id, this.config['data'].policies)
);
}
//wait for all exportPolicies calls to finish
Promise.all(promises).then(function () {
console.log("ALL resolved !!");
let successMsg = this.translate.instant("policy.resources.export_policy_success",
[this.config['data'].policies.length, this.selectedDomains.length]);
this.messageHelperService.showSuccess({hide: true, message: successMsg});
}
).catch(function () {
});
}在这里,this.policyService.exportPolicies是一个异步API调用,但它从未执行&我看到的控制台msg已解析!!
在解析Promise.all数组的承诺中的所有异步API调用之后,我们如何使解析?
API调用详细信息:
export class PolicyService {
constructor ( private baseService : BaseService ) {
}
exportPolicies(domainId, policyIds) : Observable<import("@angular/common/http").HttpEvent<any[]>>{
let url = COMMON.LEGACY_API_PATH + `policy/exportPolicy/${domainId}`;
return this.baseService.postData(url, policyIds);
}export declare class BaseService {
private http;
constructor(http: HttpClient);
handleError<T>(operation?: string, result?: T): (error: any) => Observable<T>;
log(message: string, response: object): void;
deleteData(url: string, data?: any): Observable<import("@angular/common/http").HttpEvent<any[]>>;
getData(url: string): Observable<any[]>;
postData(url: string, data?: any, params?: any): Observable<import("@angular/common/http").HttpEvent<any[]>>;
putData(url: string, data?: any, params?: any): Observable<import("@angular/common/http").HttpEvent<any[]>>;
patchData(url: string, data?: any, params?: any): Observable<import("@angular/common/http").HttpEvent<any[]>>;
headData(url: string): Observable<any[]>;
static ɵfac: ɵngcc0.ɵɵFactoryDef<BaseService, never>;
}发布于 2020-08-04 15:23:44
如果我正确地看到它,exportPolicies将返回一个Observable。通过调用promises.push(this.policyService.exportPolicies(...)),可以向名为promises的数组中添加一个Observable。现在,Promise.all不知道如何处理Observable,也不执行它,而只是返回可观察到的本身。
要解决这个问题,您可以简单地将Observable转换为Promise
promises.push(this.policyService.exportPolicies(...)).toPromise();通过正确地键入promises,例如将其声明为const promises: Promise<MyType>[] = [],您可以完全避免这个问题。那么您的TypeScript编译器甚至在执行:-)之前就已经抱怨过了。
发布于 2020-08-04 15:27:45
要么将可观测值转换为承诺并使用Promise.all,要么对可观测数据使用等效的Promise.all:forkJoin
https://stackoverflow.com/questions/63249758
复制相似问题