简体   繁体   中英

Unable to return a value from an async function using firestore

I am new to async and am trying to return a value from a Firestore db using node.

The code does not produce any errors, nor does it produce any results!

I want to read the db, get the first match and return this to the var country.

const {Firestore} = require('@google-cloud/firestore');

const db = new Firestore();

async function getCountry() {
    let collectionRef = db.collection('groups');
    collectionRef.where('name', '==', 'Australia').get()
    .then(snapshot => {
    if (snapshot.empty) {
      console.log('No matching documents.');
      return "Hello World";
    } 

    const docRef = snapshot.docs[0];
    return docRef;
  })
  .catch(err => {
    console.log('Error getting documents', err);
  });
}


let country = getCountry();

When you declare an function async , that means it always returns a promise. It's generally expected that the code inside it will use await to deal with other promises generated within that function. The final returned promise will resolve with the value returned by the function.

First of all, your async function should look more like this:

async function getCountry() {
    let collectionRef = db.collection('groups');
    const snapshot = await collectionRef.where('name', '==', 'Australia').get()
    if (snapshot.empty) {
        console.log('No matching documents.');
        // you might want to reconsider this value
        return "Hello World";
    } 
    else {
        return snapshot.docs[0];
    })
}

Since it returns a promise, you would invoke it like any other function that returns a promise:

try {
    let country = await getCountry();
}
catch (error) {
    console.error(...)
}

If you can't use await in the context of your call to getCountry(), you will have to handle it normally:

getCountry()
.then(country => {
    console.log(country);
})
.catch(error => {
    console.error(...)
})

The moment you sign up to use async/await instead of then/catch, things become much different. I suggest reading up more on how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM