Get back empty nodejs + firebase

Asked

Viewed 52 times

0

Personal I need help with a get return with Node and firebase.

receive an empty array.

but in the console.log inside the foreach prints correct

[ { cnpj: '03052164798-000179', address: 'Av Duque de 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
}

1 answer

0

Erikson, the firebase get is being asynchronous, so you give the Return even before the business array is filled.

You can pass getEmpresas to return a Promise, then when using this method, you do return then or use await:

//Método
async getEmpresas() {
  return new Promise( (resolve, reject) => {
    let empresas = [];

    firebase.firestore().collection('empresa').get().then(snapshot => {
      snapshot.docs.forEach(empresa => {
        empresas.push(empresa.data());
        console.log(empresas);
      });

      resolve(empresas);
    });
  });
}

//Consumo com then
getEmpresas()
  .then( empresas => {
    console.log(empresas);
  });

//Comsumo com wait
let empresas = await getEmpresas();

Another way would be to make the consumption of firebase synchronous with await:

async getEmpresas() {
    let empresas = [];
    let snapshot = await firebase.firestore().collection('empresa').get();

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

    return empresas;
}

There are many other ways, gives a researched on async/await, helped me a lot for cases similar to yours:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/funcoes_assincronas

Browser other questions tagged

You are not signed in. Login or sign up in order to post.