Erikson William
Erikson William

Reputation: 21

Get back empty nodejs + firebase

Guys I need some help with a get return with node and firebase.

I get an empty array.

but in console.log inside foreach prints correct

[{cnpj: '03052164798-000179', Address: 'Av Duke of Caxias 99999', Name: 'Testing', Tel: '999999999'}]

getEmpresas() {
    let empresas = []

    firebase.firestore().collection('empresa').get().then(snapshot => {

      snapshot.docs.forEach(empresa => {

        empresas.push(empresa.data())
        console.log(empresas)
      });

    })
    return empresas

Upvotes: 1

Views: 154

Answers (2)

Asaf Aviv
Asaf Aviv

Reputation: 11800

As imjared said in his answer, the function returns before .get() gets executed because it is an asynchronous function

You will need to return the chain of firebase functions which will return a Promise

getEmpresas() {
  return firebase.firestore().collection('empresa').get().then(snapshot => (
    snapshot.docs.map(({ data }) => data())
  ))
}

Then to access the returned Promise use .then() on the Promise or await inside an async function

getEmpresas.then(empresas => console.log(empresas))

Or inside an async function

const main = async () => {
  const empresas = await getEmpresas()
  console.log(empresas)
}

main()

Upvotes: 0

imjared
imjared

Reputation: 20554

I think this is a question about async. You're not getting the data you expect in the return because that fires before the async request is made. You'd need something like:

const getEmpresas = async () => {
  let empresas = []

  const snapshot = await firebase
    .firestore()
    .collection('empresa')
    .get();

  snapshot.docs.forEach((empresa) => {
    empresas.push(empresa.data());
  });

  return empresas;
};

Upvotes: 2

Related Questions