vue.js 中后端的持续轮询

Sha*_*dog 6 polling vue.js

我有一个 vue.js 应用程序,我正在集成第三方支付提供商支持。它的工作方式是 UI 向后端发送支付请求,后端对其进行处理,向 PSP 发送请求,并返回重定向 url。然后,前端需要重定向到用户通过 PSP 进行身份验证的 URL。

由于与 PSP 的通信是在后端异步处理的,并且我没有从后端到前端的双向通信,因此我的前端本质上需要不断轮询后端,询问“我们有重定向 url 吗?” 一遍又一遍地。

我的第一个天真的方法是显示一个组件(通过 v-if,当“初始化付款”请求返回 OK 时),在组件中我有这个:

 mounted() {
        setInterval(this.pollForRedirect, 1000);
    }
Run Code Online (Sandbox Code Playgroud)

我这样做是为了继续开发,但它看起来相当粗糙。有没有最佳实践方法可以做到这一点?也许是 vue 原生的东西?

我是否应该定期增加轮询间隔,以便在处理时间比预期长的情况下不会向服务器发送垃圾邮件?当用户放弃并离开组件时,如何停止轮询?

and*_*ndy 9

在 reddit 上找到了这个对我有用的解决方案:

data() {
    return {
        status: null,
        pollInterval: null
    }
},
    
    ...

methods() {
    fetchData() {
        axios.get('r/http://api/process/status')
            .then((response) => {
                //check if status is completed, if it is stop polling 
                if (response.data.status = 'completed') {
                    clearInterval(this.pollInterval) //won't be polled anymore 
                }
                this.status = response;
            });
    }
},

mounted() {
    this.fetchData()
    //check if the status is completed, if not fetch data every 10minutes.     
    if (this.status.status != 'completed') {
        this.pollInterval = setInterval(this.fetchData(), 600000) //save reference to the interval
        setTimeout(() => { clearInterval(this.pollInterval) }, 36000000) //stop polling after an hour
    }
}
Run Code Online (Sandbox Code Playgroud)


8bi*_*ero 6

我认为安迪上面的答案可能应该是这个问题的公认答案,但为了完整性和其他任何偶然发现这个问题的人:

如果您正在寻找一个简单的解决方案,要求您在不改变时间的情况下持续轮询后端(即检查价格变化),您可以尝试如下操作:

new Vue({
  el: '#pollingExample',
  data: {
    discountedProducts: []
  },
  methods: {
    loadData: function () {
      $.get('/store/discounts', function (response) {
        this.discountedProducts = response.discountedProducts;
      }.bind(this));
    }
  },
  mounted: function () {
    //Initial Load
    this.loadData();
    //Run every 30 seconds
   var loadData = function(){
        this.loadData();
        // Do stuff
        setTimeout(loadData, 30000);
   };
     setTimeout(loadData,30000);
  }
});

<div id="pollingExample">
  <div v-for="product in discountedProducts">{{ product.name + "-" +product.price + "$" }}</div>
</div>
Run Code Online (Sandbox Code Playgroud)

安装实例后,我们加载初始数据,并在setTimeout我们的帮助下安排函数每 30 秒运行一次。