【问题标题】:Vue 2.X - Good approach towards waiting for contrasting async data sources in a componentVue 2.X - 在组件中等待对比异步数据源的好方法
【发布时间】:2020-12-12 00:08:07
【问题描述】:

在一个 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 
      };
  };

【问题讨论】:

    标签: javascript vue.js vuejs2 promise vue-component


    【解决方案1】:

    只要两个函数都返回一个承诺,就使用async 生命周期钩子和Promise.all。无论该承诺是来自 http 请求还是只是从方法返回,它都有效:

    async mounted() {
      const p1 = axios.get('getData');      // not awaited, just returning promise
      const p2 = this.getOtherData();       // not awaited, just returning promise
    
      // awaiting both, responses will be in `response1` and `response2`
      const [ response1, response2 ] = await Promise.all([p1, p2]);    
      this.loading = false;
    }
    

    如果您不直接使用 http 承诺,请确保所有函数都返回承诺:

    getData() {
      ...
      return request;
    },
    getOtherData() {
       ...
       return request;
    }
    

    【讨论】:

    • 查看我的编辑。我知道 axios 的这种方法,但是对于 axios 和非 anxios 函数,我该如何做呢?
    • 其他函数应该返回一个承诺,然后它仍然可以以相同的方式工作。在getOtherData 末尾尝试return request。我进行了编辑以显示该钩子代码
    • 您的解决方案似乎不起作用pastebin.com/wYmgU4HF
    • 您尚未在任何地方设置要记录的变量。而且您没有在 任何一个函数 中返回承诺。它应该是return this.$axios... 中的getDatareturn requestgetOtherData 的末尾。仔细研究答案
    • 这应该让一切都清楚:jsfiddle.net/sh0ber/wju39z7b
    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多