封装成函数
function createSocket(url,msg){
return new Promise(function(resolve, reject){
const socket = new WebSocket(url)
socket.onopen = () => {
socket.send(JSON.stringify(msg))
setTimeout(()=>{ //当服务未回应时,判断socket状态,若不为1表示失败,做链接失败处理
if(socket.readyState!=1){
reject('error');
}
},1500)
}
socket.onerror = (e) => { //websocket链接失败
reject('error');
}
socket.onmessage = (e) => { //websocket链接成功
resolve('success');
}
})
}
调用:
createSocket(url,mgs).then(res=>{
console.log("res",res);
}).catch(err=>{
// 链接失败表示无守护进程,复用之前的逻辑
console.log(err);
}
})