如何使nodejs websocket请求/响应同步

时间:2017-05-22 05:21:27

标签: javascript ecmascript-2017

当我遇到websocket ws.send(msg)ws.on('message', ...)时,我遇到了在nodejs中实现同步编程模式的问题。我在下面的伪代码片段中描述了我的要求。

ws.on('message', (data) => {
    let msg = JSON.parse(data)
    if (msg.MsgType == 'DummyResponse') {
        // we got one response and we need to send it to the 
        // corresponding RequestID's getResponse() function
        requestMap.get(msg.RequestID).unblockingGetResponse(msg)
    }
}   

async ctx => {
    ctx.body = await ws.send({MsgType:'DummyRequest', RequestID: uuid()}).getResponse()
}

我的nodejs package.json dependencis

"dependencies": {
    "koa": "^2.2.0",
    "koa-router": "^7.1.1",
    "uuid": "^3.0.1",
    "ws": "^3.0.0"
}

我的问题是如何在es6 / 7中正确实现这个?

1 个答案:

答案 0 :(得分:0)

我使用这种模式解决了这个问题:

let resolveMap = new Map()

ws.on('message', (data, flags) => {
     let response = JSON.parse(data) 
     resolveMap.get(response.requestId)(response)
     resolveMap.delete(response.requestId)
}

async function() {
    //...
    let response = await new Promise((resolve, reject) => {
        resolveMap.set(request.requestId, resolve)
        ws.send(request)
    }
}