Promise.all打字稿不会进行异步调用

时间:2020-08-04 15:06:57

标签: javascript angular typescript es6-promise angular-promise

我正在尝试拒绝。异步API调用并希望在Promise中进行处理。毕竟已返回并解决了所有问题。

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调用,但从未执行过,并且我看到所有已解决的控制台消息!

在解决 promises 数组中的所有异步API调用之后,如何解决Promise.all?

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>;
}

2 个答案:

答案 0 :(得分:1)

如果我正确看到它,则KG返回一个exportPolicies。通过调用Observable,您可以将promises.push(this.policyService.exportPolicies(...))添加到名为Observable的数组中。现在promises不知道如何处理Promise.all,只是不执行它,而只是返回可观察的自身。

要解决此问题,您只需将Observable转换为Observable

Promise

您可以通过正确输入promises.push(this.policyService.exportPolicies(...)).toPromise(); (例如,通过将其声明为promises。那么您的TypeScript编译器甚至在执行:-)之前就已经抱怨过。

答案 1 :(得分:0)

或者将您的可观察对象转换为Promises并使用Promise.all,或者对可观察对象使用与Promise.all等效的对象:forkJoin