如何将websocket的send和onmessage改造成promise?

如题,


第一步: ws.send(JSON.stringify(query));

第二部:服务器会在收到收到参数后将查询结果data返回给前端,前端收到onmessage事件

这个怎么改造成promise的写法?可以用类似.then(console.log(data))来拿到数据?..


12345678_0001
浏览 3604回答 2
2回答

饮歌长啸

// 每一个实例都只能open一条socket线路,用锁机制防止重复open// 本例中不使用心跳检测,为了方便,只要close是非主动触发且前端能捕捉到的(如浏览器主动断开,服务器主动断开),都会进行自动重连export default class MyWebSocket {  constructor(url) {    this.url = url;    // close来源判断及后续操作    this.closeConfig = {      resolve: null,      closing: false    }    // promise池    this.promisePool = {};  }  tokenCheck(req, rsp) {    // 此处根据自己的数据结构进行tokenCheck的判断,返回一个boolean  }  open() {    return new Promise((resolve, reject) => {      if (typeof this._websocket === 'undefined') {        this._websocket = new WebSocket(this.url);        this._websocke.open = (e) => {          resolve({e, ws: this});        };        this._websocket.onerror = (e) => {          reject(e);        }      }      this._websocket.onclose = (e) => {        // 非主动close        if (!this.closeConfig.closing) {          console.log('reconnect');          // 对应的重连操作        }        // 若手动close,恢复初始状态        this.closeConfig.closing = false;      }      this._websocket.onmessage = (e) => {        const key = e.content.token;        const req = this.promisePool[key]        req.resolve(e);        delete this.promisePool[key];      };    });  }  close() {    this.closeConfig.closing = true;    this._websocket.close();  }  // token包含在content中  send(name, content) {    return new Promise((resolve, reject) => {      this.promisePool[content.token] = {        content,        resolve,        reject,        name      };      this._websocket.send({name, content});    });  }

MM们

function getMsg() {    return new Promise((resolve, reject) => {        ws.onmessage = (e) => {               resloce(e)        }    })}getMsg.then(res => {    // dosomething})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript