Vue.js 中的 Async / Await 方法

Lib*_*bra 3 javascript async-await vue.js vue-component vuejs2

我有这个相当简单的Vue组件(去掉了不必要的部分):

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');
            })
        }
    }
})  
Run Code Online (Sandbox Code Playgroud)

getTreeView()在挂载时,我调用从数据库获取数据的方法,将其保存在变量中tree,然后调用setUpTree()使用该jstree库创建树的方法。当我在日志中运行它时,我看到

4. TREE LOADED AND VISIBLE
1. GOT DATA
2. TREE SET UP
3. SET UP COMPLETE
Run Code Online (Sandbox Code Playgroud)

也就是说,流程在调用 后继续getTreeView()。现在,如果我想等到getTreeView()完成以便4. TREE LOADED AND VISIBLE最后真正打印日志该怎么办?

我尝试async/await如下:我改变了

mounted: function(){
        this.getTreeView()
        console.log('4. TREE LOADED AND VISIBLE');;
    }
Run Code Online (Sandbox Code Playgroud)

进入

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

但我得到了和以前一样的结果。如果遵循此问题的答案,则相同。我怎样才能等待该方法getTreeView()完成?

请注意,这是一个简化的示例,因为我想了解它是如何工作的,而不仅仅是因为日志的顺序很重要。

Nik*_*vic 5

也尝试等待方法:

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');
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

在已安装的挂钩中:

async mounted(){
    await this.getTreeView();
    console.log('4. TREE LOADED AND VISIBLE');
}
Run Code Online (Sandbox Code Playgroud)