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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM