在nodejs中有类似boost :: thread的东西可以异步运行函数吗?

时间:2017-09-26 03:43:49

标签: node.js asynchronous nonblocking

我使用websockets每秒约30条消息获取数据。我希望将收到的消息(对象)作为custom function传递给parameter

function有点慢(耗时,与DB相关的查询),我希望函数运行asyncparallel即不等待函数完成,即传递新收到的消息从websocketfunction尽快,我不希望从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) ;

                    });

                }
            }
        });

    });
}

我如何在异步中执行此类操作?

0 个答案:

没有答案