Javascript Vue 2.X—在组件中等待对比异步数据源的好方法

Javascript Vue 2.X—在组件中等待对比异步数据源的好方法,javascript,vue.js,vuejs2,promise,vue-component,Javascript,Vue.js,Vuejs2,Promise,Vue Component,在一个Vue组件中,我有两个来自不同来源的数据异步调用(一个是HTTP调用,一个是浏览器缓存调用),我希望有一个加载程序旋转,直到两者都完成。当两者都完成时,可以说组件已加载 ... data() { return { loading: true } }, mounted: function() { this.getData(); // HTTP Async API this.getOtherData(); // IndexedDB Async API

在一个Vue组件中,我有两个来自不同来源的数据异步调用(一个是HTTP调用,一个是浏览器缓存调用),我希望有一个加载程序旋转,直到两者都完成。当两者都完成时,可以说组件已加载

...
data() {
    return {
      loading: true
    }
},
mounted: function() {
    this.getData(); // HTTP Async API
    this.getOtherData(); // IndexedDB Async API 
},
...
我试图找出当两个都返回数据时将加载设置为false的正确方法。我目前使用标志的方法看起来很糟糕,但我不确定这是否是最好的方法

...
data() {
    return {
      loading: true,
      flagA: false,
      flagB: false
    }
},
mounted: function() {
    this.getData(); // HTTP Async API
    this.getOtherData(); // IndexedDB Async API 

},
methods: {
  getData() {
   ...
   //Once done
   this.flagA = true
   if (this.flagA == true && this.flagB == true) this.loading = false
  },
  getOtherData() {
   ...
   //Once done
   this.flagB = true
   if (this.flagA == true && this.flagB == true) this.loading = false
  }
...
有更好的方法吗

编辑以显示非HTTP功能:

getOtherData() {
    var request = indexedDB.open("Database", 1);
    request.onerror = event => {
        //IndexedDB is not supported. Resort to fallback option and continue regular program flow
    };
    request.onsuccess = event => {
      this.db = event.target.result;

      var transaction = this.db.transaction(["project"], "readwrite");

      var projectStore = transaction.objectStore("project");
      var projectReq = projectStore.get(1);

      projectReq.onsuccess = () => {
        this.flagB = true;
      };
      projectReq.onerror = () => {
        //error 
      };
  };

只要这两个函数都返回承诺,就使用
async
生命周期挂钩和
promise.all
。无论该承诺是来自http请求还是仅从方法返回,它都可以工作:

async-mounted(){
const p1=axios.get('getData');//没有等待,只是返回承诺
const p2=this.getOtherData();//没有等待,只是返回承诺
//在等待这两个响应时,响应将出现在'response1'和'response2'中`
const[response1,response2]=等待承诺。所有([p1,p2]);
这一点:加载=错误;
}
如果不直接使用http承诺,请确保所有函数都返回承诺:

getData(){
...
返回请求;
},
getOtherData(){
...
返回请求;
}

请参见我的编辑。我知道这种方法适用于axios,但如何才能适用于axios和非anxios函数?其他函数应该返回一个承诺,然后它仍然可以以相同的方式工作。在
getOtherData
的末尾尝试
returnrequest
。我编辑以显示钩子代码,因为您的解决方案似乎不起作用,您没有在任何地方设置要记录的变量。在这两个函数中,您都没有返回承诺。在
getData
getOtherData
末尾的
returnrequest
中,它应该是
return this.$axios…
。仔细研究答案这应该让一切都清楚: