【问题标题】:How to convert an http.get.("URL").subscribe to a promise so that I can await it?如何将 http.get.("URL").subscribe 转换为承诺,以便我可以等待它?
【发布时间】:2023-04-01 21:05:01
【问题描述】:

如何将 http.get.subscribe 转换为 await 以便在继续执行下一个代码之前等待它? 有问题的功能是这样的:

async ngOnInit() {
    await this.setupIngredients();

    console.log("this text should be displayed after FINISHED");
    otherCode();
    //....other code
}

我希望otherCode()console.log("this text should be displayed after FINISHED");setupIngredients() 完成后执行。

我的 setupIngredients 函数是这样的:

setupIngredients() {
    this.indicatorDataService.http.get(this.baseGetUrl + "entity=ingredients&indicator=all").subscribe(res => {
        // do something with res


    });
}

我仍然不知道为什么它不能转换为正确的 Promise。我尝试用 toPromise 替换 subscribe,但还是不行。

【问题讨论】:

    标签: promise async-await subscribe


    【解决方案1】:

    我通过将订阅包装成这样的 Promise 解决了这个问题:

    setupIngredients() {
        return new Promise(resolve => {
                this.indicatorDataService.http.get(this.baseGetUrl + "entity=ingredients&indicator=all").subscribe(res => {
                // do something with res
                resolve();
            });
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2020-07-13
      • 2020-08-17
      • 2018-12-25
      • 2019-04-29
      • 2016-11-24
      相关资源
      最近更新 更多