[我正在尝试从Firebase读取数据,在其中,我通过一个简单的查询按提供的名称检索组织。
我面临的挑战是查询工作正常并且可以检索数据,但是在执行流程中,读出实际数据的逻辑太迟了。
我认为这与我处理Observable的方式有关,但是我真的很困惑。
这是我的代码:
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。
如何确保在读出数据之前阻止逻辑的执行?
此代码:
console.log("5. Found item: " + foundName);
if(_.isNil(foundName)) {
console.log("6. return false")
return false;
}
console.log("6. return true")
需要在subscribe
回调中。由于Observables
用于异步代码,因此,当您检索数据时,subscribe
之后的代码将被称为first,而当数据被完全检索时,将被称为subscribe
内部的代码。 。