【问题标题】:Continuous polling of backend in vue.jsvue.js 中后端的连续轮询
【发布时间】:2020-05-08 16:24:19
【问题描述】:

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

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

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

 mounted() {
        setInterval(this.pollForRedirect, 1000);
    }

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

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

【问题讨论】:

  • 你考虑过使用 websockets 吗?
  • 我受到项目架构的限制,前端是 vue.js,后端是 REST API 端点。我没有双工。
  • 可能是网络工作者?
  • 不,考虑到您的限制,我会这样做

标签: vue.js polling


【解决方案1】:

在 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
    }
}

【讨论】:

    【解决方案2】:

    我认为安迪上面的答案可能应该是该问题的公认答案,但为了完整起见以及其他任何偶然发现此问题的人:

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

    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>
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 2012-01-30
      相关资源
      最近更新 更多