第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

12345678_0001 2019-03-06 18:23:38
如題,第一步: ws.send(JSON.stringify(query));第二部:服務器會在收到收到參數(shù)后將查詢結果data返回給前端,前端收到onmessage事件這個怎么改造成promise的寫法?可以用類似.then(console.log(data))來拿到數(shù)據?..
查看完整描述

2 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

// 每一個實例都只能open一條socket線路,用鎖機制防止重復open

// 本例中不使用心跳檢測,為了方便,只要close是非主動觸發(fā)且前端能捕捉到的(如瀏覽器主動斷開,服務器主動斷開),都會進行自動重連

export default class MyWebSocket {

  constructor(url) {

    this.url = url;


    // close來源判斷及后續(xù)操作

    this.closeConfig = {

      resolve: null,

      closing: false

    }

    // promise池

    this.promisePool = {};

  }


  tokenCheck(req, rsp) {

    // 此處根據自己的數(shù)據結構進行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,恢復初始狀態(tài)

        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 關注
  • 3553 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號