【发布时间】:2020-05-06 03:53:58
【问题描述】:
我正在尝试从 Firebase 中读取数据,在一个简单的查询中,我通过提供的名称检索组织。
我面临的挑战是查询工作正常并且可以检索数据,但是在执行流程中,读取实际数据的逻辑启动得太晚了。
我认为这与我处理 Observables 的方式有关,但我真的被卡住了。
这是我的代码:
async getOneOrganizationByName(name: string) {
console.log("2. Doing the check");
const query = this.afs.collection<Organization>('organizations', ref => ref.where('name', '==', name).limit(1));
return query.snapshotChanges().pipe(
debounceTime(500),
take(1),
map(
changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Organization;
data.id = a.payload.doc.id;
console.log("3. From the check logic: " + data.name);
return data;
});
}
)
);
}
async nameExists(name: string) {
if(_.isNil(name)) {
return false;
}
console.log("1. Before the check");
let foundName: string;
(await this.getOneOrganizationByName(name)).subscribe((organizations: Organization[]) => {
foundName = organizations[0].subdomain;
console.log("4. Set item: " + organizations[0].subdomain);
});
console.log("5. Found item: " + foundName);
if(_.isNil(foundName)) {
console.log("6. return false")
return false;
}
console.log("6. return true")
return true
}
从上面的代码中,我希望在控制台输出中看到:1、2、3、4、5、6 以及相应的消息,但我得到 1、2、5、6、3、4。
如何确保在数据被读出之前阻塞逻辑的执行?
【问题讨论】:
-
将代码放入订阅回调中。
标签: angular firebase async-await observable angularfire