VUE中自己實現一個輪詢方式的watch/watcher
阿新 • • 發佈:2020-11-03
背景
做即時聊天, 使用到websocket, 使用websocket代替axios進行ajax請求, 要做到的是一個promise中使用websocket send方法傳送訊息(作為request), 伺服器返回這個訊息的執行資訊(作為response), 難點在於client端如何做到:
- 傳送後阻塞, 等待訊息返回結果
- 接受到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