【问题标题】:Get value from Promise [duplicate]从 Promise 中获取价值 [重复]
【发布时间】:2017-11-01 09:26:03
【问题描述】:

在调用方法中,我需要从该方法的返回值中提取一个类别数组(Category[])。我该怎么做呢。我跟不上承诺。

getCategories() : Promise<Category[]> {
    return this.http.get(this.categoriesUrl).toPromise()
        .then(response => response.json().data as Category[])
        .catch(this.handleError);
}

如何从上述 getCategories() 方法的结果中提取特定类别?这不起作用。

getCategory(id: string): Category {
 return this.getCategories()
   .filter((category: Category, index: number, array: Category[]) => {
            return category.id === id;
        });
}

【问题讨论】:

  • 你不能,你需要等待它。并在承诺之前加快速度:-)
  • 你可能应该做.then(response =&gt; response.json()).then(json =&gt; json.data),以防.json()方法返回一个promise

标签: angular asynchronous promise


【解决方案1】:

在返回的承诺上使用then

getCategories().then((categories: Category[]) => {
    console.log(categories)
});

【讨论】:

    【解决方案2】:

    你不应该使用 Promise,而应该学会接受 RxJS Observables。然后,您可以在调用函数内部订阅 Observable 的结果,并保存对组件内部数据的引用(或任何调用服务函数的类)。

    // my-service.ts
    getCategories(): Observable<Category[]> {
        return this.http.get(this.categoriesUrl)
            .map(response => response.json().data as Category[]);
    }
    
    getCategory(id: string): Category {
        return this.getCategories()
            .selectMany(Observable.fromArray)
            .filter((category: Category, index: number) => {
                return category.id === id;
            })
            .first();
    }
    
    // my-component.ts
    this.service.getCategories().subscribe((categories: Category[]) => {
        this.localCategories = categories;
    })
    

    map 函数将修改从 Observable 接收到的数据。注意:http 请求在订阅之前不会触发。

    【讨论】:

    • 我不同意。 Promise 有自己的位置,这个问题是关于 Promise 的。
    • 泰迪,我正在关注您的解决方案。我现在尝试从 getCategories() 方法返回的类别数组中提取一个类别。它不工作。我已经修改了我的原始问题以显示这一点。请你看一下好吗?
    • 您可以使用 selectMany 运算符将数组中的每个项目拆分为单独的值,然后过滤它们并获取第一个值。我将更新我的答案以证明这一点
    • 感谢您的帮助,泰迪。我正在努力。
    • 如果我的回答解决了您的问题,我将不胜感激您将其标记为正确。
    【解决方案3】:

    getCategories() 实际上并没有像您期望的那样返回数据,它实际上返回了一个承诺!

    您需要在调用此函数的代码中调用“.then”。

    这是最简单的方式。

    getCategories().then(categories => {
        console.log(categories);
    });
    

    Promise 是链式的,所以你总是需要在链的末尾调用 then。

    【讨论】:

      猜你喜欢
      • 2018-02-24
      • 2012-09-19
      • 2020-04-30
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 2017-10-19
      • 2016-01-26
      相关资源
      最近更新 更多