Problems with Async/Await and Vuex!

Asked

Viewed 81 times

0

I am facing problems with Vuex and Javascript, I believe because I am not able to work well with Promises, Vuex and Async/Await

I have a function that runs through an array (map) Inside an if, I check if I don’t have this ID in my Vuex

Trouble comes in, I call the function this.getCentroDeCustos(itemArray.contaGerencial.id);, where its function is to just make a call and save data in vuex, but the rest of my code is not waiting for its completion and ends up saving data from my empty array because in Vuex the first time I run it is still empty.

Below my code:

getCentroDeCustosCache(arrayPraPercorrer){
    //Vou atrás dos centros de custos e jogo em cache
    let nomeCentroDeCusto = '';
    let idCentroDeCusto = '';

    arrayPraPercorrer.map((itemArray, index) => {
        if(this.cacheCG.idContasGerenciais.indexOf(itemArray.contaGerencial.id) == -1) {
            this.getCentroDeCustos(itemArray.contaGerencial.id);
        } 

        this.cacheCG.centroDeCustos.map(itemCG => {
            if(itemCG.centroDeCusto == itemArray.centroDeCusto.replace(/\s/g,'')){
                arrayPraPercorrer[index].nome = itemCG.nome 
                arrayPraPercorrer[index].idCentroDeCusto = itemCG.id
            }
        });

    });
    alert(JSON.stringify(arrayPraPercorrer) + 'CAIUUU ***************')
    return arrayPraPercorrer;

},

This code below is the function I call that takes the new data to my vuex.

async getCentroDeCustos(idDaContaGerencial){
    await axios({
            method: "get",
            url: `/centrosdecustos/contasgerenciais/${idDaContaGerencial}`,
            responseType: "json",
            headers: {
            Authorization: `Basic ${btoa(this.loggedUser.email + ":")}`,
            Accept: "application/json",
            "Content-Type": "application/json"
            }
        }).then(response => {
            this.$store.commit('setCC', {
                itemName: 'cacheCG',
                arrayName: 'centroDeCustos',
                content: response.data
            });
            this.$store.commit('setInArray', {
                itemName: 'cacheCG',
                arrayName: 'idContasGerenciais',
                content: idDaContaGerencial
            });
        })  
},
  • 1

    You are mixing some concepts... you can clarify some doubts: which version of Vuex are you using? how is your template?

  • Vuex: 3.0.1 I changed the code structure, I commented there where the problem is going: https://codepen.io/anon/pen/dBywNz

1 answer

1

When you use async/await you don’t need to use the function then() to wait for the Promise, she will be the return of await.

An asynchronous function may contain an expression await, what pause the execution of the asynchronous function and waiting for the resolution of the Promise passed, and then resumes the execution of the asynchronous function and returns the solved value.

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

Try it like this:

async getCentroDeCustos(idDaContaGerencial){
    try {
      res = await axios({
        //headers do axios bla bla bla
        }
      })
      this.$store.commit('setCC', {
          itemName: 'cacheCG',
          arrayName: 'centroDeCustos',
          content: res.data
      });
      this.$store.commit('setInArray', {
          itemName: 'cacheCG',
          arrayName: 'idContasGerenciais',
          content: idDaContaGerencial
      });
    }catch(e){
      alert(e);
    }
  },

Browser other questions tagged

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