标签:VUE resolve 轮询 watch response ETA found tick hotArea
背景
做即时聊天, 使用到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
标签:VUE,resolve,轮询,watch,response,ETA,found,tick,hotArea 来源: https://www.cnblogs.com/lyzz1314/p/13921659.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。