vue.js - 在 VueJS 上递归发送 HTTP 请求

标签 vue.js vuejs2 vue-resource

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

最佳答案

您可以创建一个返回 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>

关于vue.js - 在 VueJS 上递归发送 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44740817/

相关文章:

javascript - 有没有办法在 Vuejs 中将 'watch' 用于本地存储?

javascript - Vue v-bind 条件本地文件

javascript - vue js 中的自定义标签 - <myTag_vue> ... </> 之间不能插入任何内容?

javascript - 使用 vuejs 2 加载外部 html

javascript - 如何加载 Three.js 文本几何形状的字体

firebase - 在 Vuejs 中放置 firebase.auth().onAuthStateChanged() 的位置

javascript - 如何在Vue-Native方法中返回React-Native组件

javascript - Vue路由器不路由到指定位置

javascript - 在 Vue.js 中包含全局函数