0

I'm using an async function to get data from a collection in firebase:`

let teste = async function getDados(db)
{
  const snapshot = await db.collection('place').doc('House').collection('user').get();
  snapshot.forEach((key) => {
  console.log(key.id, '=>', key.data());
});
return snapshot
}

console.log("test", teste)

however, when displaying the variable, the result is:

test [AsyncFunction: getDados]

How do I save the result that is displayed in the console.log in the function, in a variable?

Thank you! The final code:

async function getDados(db)
{
  const snapshot = await db.collection('place').doc('House').collection('user').get();
  let results = [];
  snapshot.forEach((key) => {
    results.push(key.id, key.data());
    console.log(key.id, '=>', key.data());  
  });
  return results
}

async function teste2()
{
let teste = await getDados(db);

console.log("test", teste);
}

teste2();
  • 1
    You didn't *call* the function -- add parentheses to `teste()`. Secondly, when you *do* call it, you will get a Promise object. – trincot Mar 30 '21 at 21:50

2 Answers2

1

You did in fact did not call the function. You could try something like,

async function getDados(db)
{
  let results = [];
  const snapshot = await db.collection('place').doc('House').collection('user').get();
  snapshot.forEach((key) => {
  results.push(key.id);
  console.log(key.id, '=>', key.data());
});
return results;
}

const teste = await getDados(db);
console.log("results ", teste);

I'm not sure about the key.data() portion of your code, so I just referenced key.id

1

You're storing the function getDados inside the variable teste, then if you use typeof teste the result will be function. You can call the function getDados with teste(db), but if you want to store the return of getDados inside the variable teste you can use the following code:


async function getDados(db)
{
  const snapshot = await db.collection('place').doc('House').collection('user').get();

  snapshot.forEach((key) => {
    console.log(key.id, '=>', key.data());
  });
  return snapshot
}

let teste = await getDados(db);

console.log("test", teste);

Remember to use await inside an async function if your project uses Node on version prior to v14.3.0, which supports top-level await.