Shreyas Achar
Shreyas Achar

Reputation: 1435

Fetch values from Firestore and store the output as global using async

I am trying to fetch the firestore data and then store it in a variable

async function getchildContent(Parent, Message) {
    let count = 0;
    var db = firebase.firestore();
    var output = db.collection("rooms").doc(Parent).collection("messages").where("ParentId", "==", Message).get().then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
        })

    });

    return output;
}

This function i am calling as

var dataAll ={};
getchildContent(PDocId, doc.id).then(result=>{
    dataAll = result;
});

console.log(dataAll);

If i assign it as

var output = getchildContent(PDocId, doc.id);

Then the result will br promise {pending}

But I am getting an empty array output, How to resolve this?

Upvotes: 0

Views: 60

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50840

You should handle the promises using either a promise chain or async-await. It seems you want to use async await syntax so try this:

async function getchildContent(Parent, Message) {
  let count = 0 ; 
  const db = firebase.firestore();
  const querySnapshot = await db.collection("rooms").doc(Parent).collection("messages").where("ParentId","==",Message).get()
  const data = querySnapshot.map.docs((doc) => doc.data())
  return data
});
             
// This should be inside of an async function as you need to use await.
const output = await getchildContent(PDocId, doc.id);
// If you are using promise chainging
let output = null

getchildContent(PDocId, doc.id).then((data) => {
  console.log(data)
  output = data

  // logging output here will log the value
  // proceed code execution within then block
})

// If you log output here, it'll be null as then promise above will not be resolved

Upvotes: 1

Related Questions