首页 > 解决方案 > 如何将 http.get.("URL").subscribe 转换为承诺,以便我可以等待它?

问题描述

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

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

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

我希望otherCode()and完成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,但它仍然不起作用。

标签: promiseasync-awaitsubscribe

解决方案


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

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

推荐阅读