Home > Blockchain >  If condition after result of Promise
If condition after result of Promise

Time:04-14

I have a problem with a promise. I have this function that is used to comunicate with Firestore database:

  async getDataFromDB() {
    const junctionRef = firebase
      .firestore()
      .collection('junction')
      .doc(this.id)
      .collection('items')
      .doc(this.userId);
    return await junctionRef.get().then((doc) => {
      const details = doc.data();
      return details;
    });
  }

In ngOnInit method I call this funtion and, based on the result of this promise, I want to set some values:

  ngOnInit() {
    ....
    this.getDataFromDB().then((data) => {
      if(data != null && data.numbers<10 )
        // TO SOMETHING
    });

But it never enters the if because data tells me it is undefined . How can I solve it ?

CodePudding user response:

Try to use Promise. Something like this.

getDataFromDB(): Promise<any>
return new Promise((resolve, reject) => {
const junctionRef = firebase
      .firestore()
      .collection('junction')
      .doc(this.id)
      .collection('items')
      .doc(this.userId);

junctionRef.get().then((doc) => {
      const details = doc.data();
      resolve(details);
    });

CodePudding user response:

Try this approach:

async ngOnInit() {
    try {
        this.loading = true;
        const commerces = await this.db.getCommerces();
        this.dataSource = new MatTableDataSource(commerces);
    } catch (error) {
        // Your logic to handle the error
    } finally {
        this.loading = false;
    }
}

database.service.ts

public async getCommerces() {
    let commerces: Commerce[] = [];
    try {
        const colRef = collection(this.db, COLLECTION_COMMERCES);
        const docs = await getDocs(colRef);
        if (docs.size <= 0) throw 'size-error';
        docs.forEach(item => commerces.push(item.data() as Commerce));
        return commerces;
    } catch (error) {
        throw error;
    }
}

In general, when you want to return correct data, you just return it, and when you want to handle errors, you have to do it with a throw. At least firebase is programmed like this. And I find that the code is more readable.

  • Related