如何使用vue资源定期在页面加载时轮询后端api?

时间:2016-09-23 18:52:19

标签: javascript ajax vue.js

在向api提交表单后,如果表单数据已更新并显示状态,则会显示一个加载页面,需要每隔1秒检查一次,超时为60秒。有没有办法继续重试ajax请求并使用vue-resource选项设置时间间隔和超时?在documentation中,他们有超时选项,但没有间隔。以下是我到目前为止的情况:

<template>
  <div v-if="location === 'updated'">Location Updated!</div>
  <div v-if="location === 'error'">Update failed, check back later!</div>
  <div v-if="location === 'pending'">Loading...</div>
</template>

<script>
 ...

 data: function() {
   return { orderStatus: 'pending' }
 }

 ready: function() {
   this.$http.get('/location/12', { timeout: 60000, interval: 1000 } ).then((response) => {
        this.orderStatus = response.body.order_status
     }
   }
</script>

1 个答案:

答案 0 :(得分:0)

Web套接字应该是理想的答案。

但如果您的目标是查看表单数据是否已更新,则可以按照这些方式进行轮询

简单而不延期

(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);
})();

延期:

// 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);