【问题标题】:Promise<any> being converted into ZoneAwarePromisePromise<any> 被转换为 ZoneAwarePromise
【发布时间】:2018-11-04 13:05:11
【问题描述】:

我在我的项目中使用 Angular5。我在我的 api 服务中实现了返回承诺的方法

method(): Promise<any> {
    return new Promise<any>((resolve,reject) => {
        this.http.get(url).subscribe((response) => {
            resolve(response);
        }, (error) => reject(error));
    });
}

在组件中,需要确保在进一步操作之前已获取所有数据。我试着这样做:

const fetch = [];
fetch.push(this.api.method());
fetch.push(this.api.method1());
fetch.push(this.api.method2());

Promise.all(fetch).then(() => alert('data fetched')); 

它从未达到警戒状态。代码 200 全部成功。

当我在 Promise.all 处暂停执行时,我看到我的 Promise(s) 已转换为 ZoneAwarePromise

当我将它们链接到 .then(s) 中的嵌套调用时效果很好

为什么 Promise 被转换了?如何让 Promise.all 工作?

【问题讨论】:

  • Angular 封装了所有变更检测的承诺。
  • 您能否在 stackblitz 上创建一个简短的“不”工作示例?这似乎应该工作。此外,您可以在 rx 管道上使用.toPromise(),而不是自己构建承诺。
  • 它对 Promise.all 有何影响?使用 Angular 时是否必须实现自己的 .all()?
  • 不,你可以在 Angular 中使用 .all
  • 你确定你的method1和method2也解析了observable吗?没有 stackblitz 就很难调试,而且到目前为止你发布的代码看起来应该可以工作

标签: javascript angular typescript promise zone


【解决方案1】:

使用forkJoin 代替Promise.all 怎么样?通过执行以下操作:

forkJoin(...fetch.map(yourPromis(url)))

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多