• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

320
Views
Método Async/Await en Vue.js

Tengo este componente Vue bastante simple (despojado de partes innecesarias):

 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'); }) } } })

En el montaje, llamo al método getTreeView() que obtiene los datos de la base de datos, los guarda en el tree de variables y luego llama a setUpTree() que crea un árbol usando la biblioteca jstree . Cuando lo ejecuto en el registro veo

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

es decir, el flujo continúa después de la llamada a getTreeView() . Ahora, ¿qué pasa si quiero esperar hasta getTreeView() para que el registro 4. TREE LOADED AND VISIBLE se imprima en último lugar?

Probé con async/await de la siguiente manera: cambié

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

dentro

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

pero obtuve el mismo resultado que antes. Lo mismo si sigue las respuestas a esta pregunta . ¿Cómo puedo esperar a que finalice el método getTreeView() ?

Tenga en cuenta que este es un ejemplo reducido porque quiero entender cómo funciona, no solo porque el orden del registro importa.

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Intenta esperar el método también:

 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'); }) } }

en gancho montado:

 async mounted(){ await this.getTreeView(); console.log('4. TREE LOADED AND VISIBLE'); }
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error