【发布时间】:2018-08-22 22:47:47
【问题描述】:
你能告诉我如何将 Angularfire2/Firestore observable 转换为 promise 吗? 我已经尝试如下所示。但它不起作用,也没有错误。
.ts
this.categories$ = this.categoryProvider.getAllContactCategories().valueChanges();
const defaultCategories = await this.categories$.map((response) => response).toPromise();//after this line it won't execute
await Promise.all(defaultCategories.map(async (c: Category) => {
await this.categoryProvider.createCategory(c.name, project.id);
}));
provider.ts
getAllContactCategories(): AngularFirestoreCollection<Category> {
return this.fireStore.collection(`contactCategories`);
}
【问题讨论】:
-
但是你愿意这样做吗?在打字稿中有不同的异步处理方式。为什么你只需要
async await? -
是的,我需要在这里使用
async/await模式,因为这只是方法的一小部分。我在整个方法中都使用了这种模式。所以这就是原因。 @NamanKheterpal -
我无法帮助您回答您的问题,但我只能建议使用这么多
await是非常糟糕的做法。 Angular 更喜欢observable而不是promises是有原因的。我可以帮助您仅使用 observable 来实现相同的结果。 -
是的,在某些用例中,我们需要使用 Promise 而不是 observable。我找到了解决方案。感谢您的反馈:) @NamanKheterpal
标签: angular typescript promise observable google-cloud-firestore