【问题标题】:Sending HTTP Request Recursively on VueJS在 VueJS 上递归发送 HTTP 请求
【发布时间】:2017-11-28 04:16:15
【问题描述】:

我已经检查了很多地方来做到这一点。但是,没有找到任何解决方案。假设,我们在任何方法中都收到了 HTTP 发布请求。我正在尝试递归调用 HTTP 发布请求。问题是,当我尝试使用 setInterval 函数执行此操作时,由于连接问题,队列中存在一些待处理的请求。当连接不足时,它会在队列中累积。我想要做的是,在发送最新请求之前不要发送请求。它的最佳做法是什么?

【问题讨论】:

  • 这是您需要的吗? jsfiddle.net/wostex/63t082p2/79
  • 显然是这样。您能否输入您的解决方案作为答案。我可以检查它的标记。这是一个非常有用的解决方案,这就是我要求它的原因

标签: vue.js vuejs2 vue-resource


【解决方案1】:

您可以创建一个返回 Promise 的函数和另一个函数,该函数解析此 Promise 并在 .then 回调中再次调用自身:

new Vue({
  el: '#app',
  data: {
    fetchCounter: 0 // used here to prevent infinite requests 
  },
  methods: {
    myFetch: function() {
      return fetch('https://jsonplaceholder.typicode.com/users/1/')
    },
    loopFetch: function() {
      this.myFetch().then(res => {
      	console.log(res.status, ' ', this.fetchCounter++);
        if (this.fetchCounter < 10) { // repeat 10 times, then abort
          setTimeout(this.loopFetch, 1000); // sort of debounce
        } else {
          console.log('aborted')
        }
      })
    }
  },
  mounted() {
    this.loopFetch(); // first call of the loopFetch function 
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多