Im trying to get the Value from my Firestore DB Async Function cvUpload. But no matter how long i wait for the value it is still undefined if i call it on my component.
I see many have the same issues with async await and promises . But i really not able to solve it. I really need some hints here.
DatabaseService.ts
export class DatabaseService {
constructor(
private dbService : DatabaseService ) {}
async cvUpload (id : string) {
const userRef = collection(this.db, this.user_db)
const q = query(userRef, where("id", "==", id));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
console.log(doc.data().cv) /// False (Thats correct)
return doc.data().cv;
});
}
DashboardComponent.ts
constructor(
private dbService : DatabaseService ) {
}
async ngOnInit() {
await this.checkCV('uyDer0BxoVekGU2XnYa3Xm77nm03')
}
async checkCV(id : any) {
let result = await this.dbService.cvUpload(id) /// This shoud return FALSE
}
I am grateful for any help or tip that will take me further here
CodePudding user response:
the actual mistake lies in the cvUpload method. You're actually returning nothing from the cvUpload function. Returning something inside a Array.forEach() doesn't count as cvUpload's return value.
Maybe you should just return
async cvUpload(id: string) {
const userRef = collection(this.db, this.user_db)
const q = query(userRef, where("id", "==", id));
const querySnapshot = await getDocs(q);
return querySnapshot.docs[0].data().cv;
};
CodePudding user response:
First of all, here:
querySnapshot.forEach((doc) => {
console.log(doc.data().cv) /// False (Thats correct)
return doc.data().cv;
...
You are doing a forEach...I guess that you are waiting to recive just 1 only item... But if not, be careful because you only would treat the first element...
Any way, assuming that you will only have one element in there:
Probably you are having problem with the "falsy" returning value...Could you try to treat all of these with an object, to check if it still happens?.
Something like this:
DatabaseService.ts
querySnapshot.forEach((doc) => {
console.log(doc.data().cv) /// False (Thats correct)
const result: {result: boolean};
result = { result: doc?.data()?.cv ?? false, };
return result;
});
DashboardComponent.ts
async checkCV(id : any) {
const {result} = await this.dbService.cvUpload(id) /// This shoud return FALSE
}
