为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

12345678_0001 2019-03-06 18:23:38
如题,第一步: ws.send(JSON.stringify(query));第二部:服务器会在收到收到参数后将查询结果data返回给前端,前端收到onmessage事件这个怎么改造成promise的写法?可以用类似.then(console.log(data))来拿到数据?..
查看完整描述

2 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

// 每一个实例都只能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});

    });

  }


查看完整回答
反对 回复 2019-03-11
?
MM们

TA贡献1886条经验 获得超2个赞

function getMsg() {

    return new Promise((resolve, reject) => {

        ws.onmessage = (e) => {

               resloce(e)

        }

    })

}

getMsg.then(res => {

    // dosomething

})


查看完整回答
反对 回复 2019-03-11
  • 2 回答
  • 0 关注
  • 3593 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号