Array being rewritten completely within foreach

Asked

Viewed 79 times

-1

I’m running a voting system through the firestore, and I’m having a problem regarding the behavior of an array within the foreach, follow the code:

         busca_votos:  function(pergunta){
            let path  =  firebase.firestore().collection('database').doc(this.id_cliente).collection('assembleia')
            let temas = []
            let valor_voto = []

            path
                .doc(this.id_assembleia)
                .collection('votos')
                .where('id_voto', '==', pergunta)
                .get().then( snapshot =>{
                    snapshot.docs.forEach( dado =>{
                        temas.push(dado.data().id_tema)
                        valor_voto.push(pergunta)
                })

            })
            console.log(valor_voto)
        },

The above function receives the parameter 'question', and in it comes an id of the question that is in the firestore, what I do in the function query is to compare if in Collection 'votes' there is this id (if there is it means that there were votes). My problem is with "valor_voto.push(question)". I would like it to push this array every time I find a value, but what happens is it "overwrites" the whole array, my result looks something like:

>[]
  0: "77784"
  1: "77784"
  length: 2

>[]
  length: 0

>[]
  0: "124520"
  length: 1

NOTE: The numbers that are printed in the array are the question id’s.

Does anyone know why you’re behaving this way? I would like it to return me an array only with all id’s voted to be able to count the times it appears ...

1 answer

2

Hello!

Actually I believe that your code is running "correctly", but what is causing this behavior in its console.log() is to call him after the .get() which is asynchronous because it returns an Promise(). To test you can put the console.log() after the forEach(), but you won’t be able to return the variable valor_votos outside the .then().

One way to solve this would be to use async/await:

async function getVotos() {
  const votos = [];

  const querySnapshot = await firestore()
    .collection('votos')
    .get();

  querySnapshot.forEach((documentSnapshot) => {
    votos.push(documentSnapshot.data());
  });

  console.log(votos);

  return votos;
};

I hope I’ve helped in some way.

  • In parts helped yes, with async I am less concerned with the fact that it follows the normal behavior of the JS. The impression I have is that it is still rewriting for some reason, follow don’t pad: https://dontpad.herokuapp.com/javascript

Browser other questions tagged

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