zoukankan      html  css  js  c++  java
  • VUE中自己实现一个轮询方式的watch/watcher

    背景

    做即时聊天, 使用到websocket, 使用websocket代替axios进行ajax请求, 要做到的是一个promise中使用websocket send方法发送消息(作为request), 服务器返回这个消息的执行信息(作为response), 难点在于client端如何做到:

    1. 发送后阻塞, 等待消息返回结果
    2. 接受到response后, 停止阻塞, 根据response内容决定前端执行状态.

    solution

    方法: setTimeout轮询, Promise阻塞. 先上代码

    let hotArea = 0; // when response comes, keep data in hotArea
    
    // simulate response from Server
    setTimeout(()=>{
      hotArea = 2;
      console.log('hotArea mutated!')
    }, 5000);
    
    
    
    new Promise((resolve, reject) => {
       // do something here...like send a message though websocket
      resolve(1);
    })
      .then((res) => {
        return new Promise((resolve,reject)=>{
          let tick = 10; // set 10 seconds
          let callBackFunction = function(){
            // check if hotArea is hit
            if(hotArea===1){
              // gotten
              let res = hotArea;
              // clear hotArea
              hotArea = 0;
              clearInterval(timer);
              return resolve(res)
            }else{
              tick = tick-1;
              console.log('not found! ETA:',tick)
              if(tick<0){
                clearInterval(timer);
                return resolve('timeOut!')
              }
            }
          };
    
          let timer = setInterval(callBackFunction, 1000);
          
          // setTimeout(resolve, 3000, hotArea);
    
        })
      })
      .then((res) => {
    
        console.log('timer generates: ',res);
    
      });
    

    执行结果:
    请求超时:

    not found! ETA: 9
    not found! ETA: 8
    not found! ETA: 7
    not found! ETA: 6
    hotArea mutated!
    not found! ETA: 5
    not found! ETA: 4
    not found! ETA: 3
    not found! ETA: 2
    not found! ETA: 1
    not found! ETA: 0
    not found! ETA: -1
    timer generates:  timeOut!
    

    请求顺利:

    not found! ETA: 9
    not found! ETA: 8
    not found! ETA: 7
    not found! ETA: 6
    hotArea mutated!
    timer generates:  1
    
  • 相关阅读:
    Fy's dota2
    Black Rock Shooter
    树上的颜色
    8.spring:事务管理(上):Spring的数据库编程、编程式事务管理
    7.spring:SpringAOP(配置文件)
    6.spring:AOP(注解)
    5.spring:注解配置 Bean
    4.spriing:Bean的生命周期/工厂方法配置Bean/FactoryBean
    3.spring:自动装配/Bean之间的关系/作用域/外部文件/spel/
    2.spring:集合属性
  • 原文地址:https://www.cnblogs.com/lyzz1314/p/13921659.html
Copyright © 2011-2022 走看看