[Vuejs]-How to poll a backend api periodically on page load with vue resource?

0👍

Web socket should be the ideal answer.

But if your goal is to see if form data has been updated, you can do polling these ways

Simple without Deferred

(function poll(){
   setTimeout(function(){
      $.ajax({ url: "server", success: function(data){
        //Setup the next poll recursively if order status is not updated
        if (orderStatus not update)
            poll()
        else
            display order status
      }, dataType: "json"});
  }, 30000);
})();

With Deferred:

// The polling function
function poll(fn, timeout, interval) {
    var dfd = new Deferred();
    var endTime = Number(new Date()) + (timeout || 2000);
    interval = interval || 100;

    (function p() {
            // If the condition is met, we're done! 
            if(fn()) {
                dfd.resolve();
            }
            // If the condition isn't met but the timeout hasn't elapsed, go again
            else if (Number(new Date()) < endTime) {
                setTimeout(p, interval);
            }
            // Didn't match and too much time, reject!
            else {
                dfd.reject(new Error('timed out for ' + fn + ': ' + arguments));
            }
    })();

    return dfd.promise;
}

// Usage:  ensure order status is updated
poll(function() {
    return response.body.order_status == "updated";
}, 2000, 150);

Leave a comment