Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

393
Visualizações
Async / Await method in Vue.js

I have this rather simple Vue component (stripped of unnecessary parts):

Vue.component('equipment-tree', {
    data(){
        return {
            tree: [],
    }
},
template: `
    <template>
        <div id="equipment_tree"></div>
    </template>`,
mounted: function(){
    this.getTreeView()
    console.log('4. TREE LOADED AND VISIBLE');;
},
methods: {
    setUpTree(){
        $("#equipment_tree").jstree("destroy");
        $('#equipment_tree').jstree({ 
            core : {
                data : this.tree,
                multiple: false,
                themes: { 
                    dots: true
                }
            },
        });
        console.log("2. TREE SET UP")
    },
    getTreeView(){
        fetch("myurl /*just a URL */", 
            {
                method: 'GET',
            })
            .then((response) => response.json())
            .then((data) => {
                console.log('1. GOT DATA');
                this.tree = JSON.parse(data.tree);
                this.setUpTree();
                console.log('3. SET UP COMPLETE');
            })
        }
    }
})  

On mount, I call the method getTreeView() that gets the data from the database, saves it in the variable tree, and then calls setUpTree() which creates a tree using the jstree library. When I run it in the log I see

4. TREE LOADED AND VISIBLE
1. GOT DATA
2. TREE SET UP
3. SET UP COMPLETE

that is, the flow continues after the call to getTreeView(). Now, what if I want to wait until getTreeView() finishes so that the log 4. TREE LOADED AND VISIBLE gets actually printed last?

I tried with async/await as follows: I changed

mounted: function(){
        this.getTreeView()
        console.log('4. TREE LOADED AND VISIBLE');;
    }

into

mounted: async function(){
        await Promise.resolve(this.getTreeView());
        console.log('4. TREE LOADED AND VISIBLE');
    }

but I got the same result as before. Same if following the answers to this question. How can I wait for the method getTreeView() to finish?

Please, note that this is a reduced example because I want to understand how it works, not just because the order of log matters.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try to wait for method too:

async getTreeView(){
    await fetch("myurl /*just a URL */", 
        {
            method: 'GET',
        })
        .then((response) => response.json())
        .then((data) => {
            console.log('1. GOT DATA');
            this.tree = JSON.parse(data.tree);
            this.setUpTree();
            console.log('3. SET UP COMPLETE');
        })
    }
}

in mounted hook:

async mounted(){
    await this.getTreeView();
    console.log('4. TREE LOADED AND VISIBLE');
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda