Search code examples
vue.jsvuejs2vue-resource

Sending HTTP Request Recursively on VueJS


I've checked many places to do that.However, not found any solution about it. Let's suppose, we have got HTTP post request in any method. I am trying to call HTTP post request recursively. The issue is, when I tried to do it with setInterval function, there are some requests pending on queue due to connectivity issues. It's accumulating on the queue while the connection is low. What I want to do is, do not send a request before latest request sent. What is the best practice for it?


Solution

  • You can create a function which returns Promise, and another function, which resolves this Promise and calls itself again in .then callback:

    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>