promise - 如何将 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,但它仍然不起作用。
解决方案
我通过将订阅包装成这样的 Promise 解决了这个问题:
setupIngredients() {
return new Promise(resolve => {
this.indicatorDataService.http.get(this.baseGetUrl + "entity=ingredients&indicator=all").subscribe(res => {
// do something with res
resolve();
});
});
}
推荐阅读
- python - scipy.stats.t.std() 中的“scale”参数代表什么?
- batch-file - 将文件批量重命名为更有意义的名称
- python - 列的总和(如果它包含多个字符串)
- python - 从 Prefect 中的 DockerRun 访问 Google 凭据密钥
- java - 如何使 java 应用程序与 ESP32 板通信?
- swiftui - 无法启动设备,因为它不能位于磁盘上。, NSLocalizedFailureReason=设备的数据不再存在
- vulkan - 从 VkImageCreateInfo 计算 VkImageAspectFlagsBits?
- python - 如何访问在 Docker 容器内运行的 Django 应用程序?
- javascript - 如何突出显示在我的传单地图(nuxt/vue)中单击了哪个标记
- r - 结合 ifelse 两个条件并循环