Vue.js and the use of Async / Await pattern

Here is a simplified version of my Vue component:

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

After calling the method getTreeView() on mount, I see in the log:

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

I wanted to wait for getTreeView() to finish before logging "TREE LOADED AND VISIBLE" last, so I tried using async/await:

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

However, I did not achieve the desired outcome. How can I properly wait for the getTreeView() method to finish executing?

Just to clarify, this example has been simplified for the sake of understanding the process, rather than focusing solely on the order of logs.

Answer №1

Consider pausing for the method as well:

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

implemented in mounted hook:

async mounted(){
    await this.fetchTreeView();
    console.log('4. TREE LOADED SUCCESSFULLY AND VISIBLE');
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I extract and display data from a MySQL database in cytoscape.js?

I have a database table called 'entrezgene' that contains geneID and name fields. These fields will be used to create nodes in cytoscape.js. Additionally, I have another table named 'interaction' with geneID and geneID2 fields, which wi ...

What is preventing the installation of bootstrap-vue on my system?

I'm facing an issue while attempting to set up bootstrap-vue in my vue project. I used the command npm install bootstrap-vue bootstrap, but encountered a perplexing error message. npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class=" ...

The smooth shading in Three.js is giving off a flat appearance

When loading .stl files, I'm using MeshStandardMaterial without adjusting the flatShading property since it is set to false by default. https://i.sstatic.net/zbCiR.png The outcome appears rather dull to me. Even when attempting to toggle flatShading ...

Transform a string into an object

How can I convert a string into an object with error details? const er= {'username': [ErrorDetail(string='A user with that username already exists.', code='unique')], 'email': [ErrorDetail(string='user with thi ...

The functionality of the mathjs eval function varies when used with and without a string input

When I calculate Arithmetic operations using the math.eval function without quotes, null values are ignored and correct results are obtained. However, if I use quotes in the same function, it throws an error. The issue is that I require strings because I ...

JQuery Resizable: A guide on creating multiple resizable divs that can be adjusted individually

I have created a basic web application that allows you to dynamically add div elements to a container div. You can preview the app here: Before resizing https://i.sstatic.net/X2o6K.png When you click the "Image" link in the left menu, a new div with a ...

When using the each() function, the array shows a length of zero and does not

Although I am well-versed in PHP, my understanding of JQuery is lacking and I'm experiencing some difficulty with arrays. Despite researching numerous forum posts on the topic, I still can't seem to get it right. I believe I have an array struct ...

Using KnockoutJS: Validate the model's property if the bound control is currently visible

On a particular page, I have a model that is connected to various controls. Depending on specific conditions, some of these controls may be shown or hidden. During the final submission, only the visible controls need to be validated. Here is an example co ...

Storing numerous sets of application credentials in Node.js using a specific design pattern

As I develop a node.JS server that communicates with Microsoft APIs, the server manages multiple applications created in Azure, each requiring a configured Client ID and Client secret. I have implemented a strategy to switch between these credentials based ...

Bring fontawesome into the Laravel environment with MDBVue integration

I attempted to integrate fontawesome into my laravel mdbvue setup. Upon installing mdbvue using the command: npm install mdbvue fontawesome was automatically added to my package-lock.json and can be found in the node_modules folder under @fortawesome. ...

What is the correct way to toggle an icon button?

Hello everyone! I need help with toggling a font-awesome icon on a button using jQuery or JavaScript. I've tried using jQuery, but the previous icon doesn't get removed from the button when toggling to the new icon. Below is the code snippet: < ...

During a jQuery ajax call, if one of the keys has the value "??", jQuery will automatically convert the value to jQuery164042601801476224854_1371690944590

When I execute the following code snippet: var i = '{"xyz":"??"}' $.ajax({ url: '/someendpoint',type: 'post', dataType: 'json', success: null,error: null,data: i }); The post request shown in Firebug is: {"xyz": ...

Ways to enhance a class that is declared but not exported in a Typescript module

The hubot type definitions contain the following class: declare namespace Hubot { // ... class Message { user: User; text: string; id: string; } // ... } // Compatibility with CommonJS syntax exported by Hubot&ap ...

Sending a json array from PHP

I spent several hours searching for solutions to my problem but couldn't find an answer. I'm trying to perform a search on the same page using jQuery, AJAX, and PHP. Unfortunately, the array from PHP is still returning undefined. Here is the P ...

if statement not recognizing data returned from PHP function

I'm currently working with a function that is being used for an AJAX query: var formData = $(this).serialize(); //store form names and values in an array called 'formData' $.get('filtertest.php',formData,processData); //jQ ...

Struggling to clear items from input field within AngularJS

I'm currently facing an issue where I am unable to delete data from an input field. var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', function MyCtrl($scope) { $scope.items = [ { name: & ...

What is the regular expression to validate a string such as '$Now + 2h' in JavaScript?

Need to validate a user input string: The string consists of two parts: Part 1 and Part 2. Part 1 must be either '$Now', '$Today' or '$CurrentMonth'. Part 1 is required. Part 2 can contain '+' or '-' foll ...

JS, Async (library), Express. Issue with response() function not functioning properly within an async context

After completing some asynchronous operations using Async.waterfall([], cb), I attempted to call res(). Unfortunately, it appears that the req/res objects are not accessible in that scope. Instead, I have to call them from my callback function cb. functio ...

Are there any missing (or "optional") expressions in handlebars.js?

Currently, I am developing a build script using Node.js. To summarize, the script carries out the following tasks: Prompting the user for essential information such as the project name and description Cloning a template from a Git repository Renaming fil ...

Switching the displayed image depending on the JSON data received

As a beginner in javascript and jQuery, I am working on displaying JSON results in the browser. My goal is to generate dynamic HTML by incorporating the JSON data. Below is an example of the JSON structure: [{"JobName":"JobDoSomething","JobStatus":2,"JobS ...