VUE中自己实现一个轮询方式的watch/watcher
背景
做即时聊天, 使用到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