我使用websockets
每秒约30条消息获取数据。我希望将收到的消息(对象)作为custom function
传递给parameter
。
function
有点慢(耗时,与DB相关的查询),我希望函数运行async
或parallel
即不等待函数完成,即传递新收到的消息从websocket
到function
尽快,我不希望从function
返回数据。所以它可以自由运行,然后用它完成。
在cpp中有
boost::thread(functionName, parameter);
我如何在nodejs
这是我在nodejs中的代码。
var WebSocketClient = require('websocket').client
var WSclient = new WebSocketClient();
WSclient.connect('127.0.0.1/ws');
WSclient.on('connect', function(conn){
console.log('connected to websocket');
conn.on('message', function (packet){
var msg = JSON.parse(packet)
processMessage(msg);
//dont wait
processMessageOtherway(msg);
});
});
function processMessage ( msgObject ){
//time consuming code
msgObject.rhand
.filter(elem => elem.isUser === false && typeof elem.name === "string")
.map(function(elem) {
//check if message is in our database
mysql_con.query("SELECT value FROM key_value WHERE key = '" + (elem.name) + "'" , function (err, result) {
if (err) throw err;
if ( result.length > 0 ){
if(result) {
data = result[0].value
//request remote page
request({
url: "http://example.com/pushValue",
method: "POST",
body: data
}, function(error, response, received_body){
console.log(received_body);
});
}
}
});
});
}
function processMessageOtherway ( msgObject ){
//time consuming code
msgObject.lhand
.filter(elem => elem.isUser === false && typeof elem.name === "string")
.map(function(elem) {
//check if message is in our database
mysql_con.query("SELECT value FROM key_value WHERE key = '" + (elem.name) + "'" , function (err, result) {
if (err) throw err;
if ( result.length > 0 ){
if(result) {
data = result[0].value
msgObject.rhand
.filter(elem => elem.isUser === false && typeof elem.name === "string")
.map(function(elem) {
console.log(elem.FullName) ;
});
}
}
});
});
}
我如何在异步中执行此类操作?