【问题标题】:Async / Await method in Vue.jsVue.js 中的异步/等待方法
【发布时间】:2021-11-19 04:00:15
【问题描述】:

我有这个相当简单的 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');
            })
        }
    }
})  

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

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

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

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

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

进入

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

但是我得到了和以前一样的结果。如果遵循this question 的答案,则相同。 如何等待getTreeView()方法完成?

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

【问题讨论】:

  • 有什么理由不让gettreeview异步,这样你就可以直接等待了吗?
  • 这不是 vue 的事情,这是异步代码的工作方式。您的函数 getTreeView 正在处理承诺,它会立即执行,但它导致的副作用会在承诺解决时发生。

标签: javascript vue.js async-await vue-component


【解决方案1】:

也尝试等待方法:

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

在挂载的钩子中:

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

【讨论】:

  • 现在可以了!但我一开始不明白:为什么要“双重等待”?为什么mountedgetTreeView() 上的await 不够用?谢谢
  • 因为你需要等到方法解析,所以其他行要执行到那时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
相关资源
最近更新 更多