簡體   English   中英

socket.io和節點回調函數不起作用

[英]socket.io and node callback functions not working

我在獲取socket.io中的異步回調和變量存儲方面確實非常困難。 我希望在進行所有查詢后執行回調函數中的代碼。 但是,我不知道將callback()方法調用放在何處,以便在一切完成后執行。 我將不勝感激任何幫助。

//The code below queries a database and stores the information in a json object.
var mysql = require('mysql')
    var io = require('socket.io').listen(3000)
    var db = mysql.createConnection({     
        host: '',
        user: '',
        password: '',
        database: '',
        port: 3306,
    })
    db.connect(function(err){
        if (err) console.log(err)
    })

console.log(1);
io.sockets.on('connection', function(socket){
   socket.on('key', function(value){//client side has a onclick() function that emits 'key'
        console.log(2);
        var total = {};
        var personalTable = []
        var liwcTable = []
        var id = value;

        help(total, function(total) {
            console.log(4);
            console.log("total = " + JSON.stringify(total));
            socket.emit('total', total);/emits to client
        });

        function help(total, callback) {
            console.log(3);
            db.query('SELECT * FROM `a` WHERE `userId` =' + id)
                .on('result', function(data){
                    liwcTable.push(data)
                })
                .on('end', function(){
                    total["initial liwcTable"] = liwcTable;
                })
            db.query('SELECT * FROM `b`  WHERE `userId` =' + id)
                .on('result', function(data){
                    personalTable.push(data)
                })
                .on('end', function(){
                    total['personalTable'] = personalTable;
                }) 
            callback(total)//needs to be executed after the queries are done.
         }
    })    
})

在查詢有機會完成之前,代碼將進入回調方法。 當查詢回調的范圍受到限制時,我也不明白如何更新json對象“ total”。

您有多種解決方案可在所有需要的操作之后觸發回調。 例如,您可以在每個查詢之后創建一個單例調用,這將觸發最終的回調。

function help(total, callback) {

    var nbEndedQueries = 0,
        amountOfQueries = 2;//nb of linked queries
    function singleton() {

        //increments the nbEndedQueries variable and tests if the max is reached
        if(++nbEndedQueries >= amountOfQueries)
            callback();
    }


    db.query(... //query calling)
        .on('result', ...//some behaviours
            singleton();
        )
    db.query(... //query calling)
        .on('result', ...//some behaviours
            singleton();
        )
    //...

}

另一種解決方案是使用諾言。 Q或ECMA6 polyfill等許多模塊都為您提供了此功能,這真是太棒了

帶有ecm6的樣品承諾填充

//promisification of the query method
function query(string) {
    return new Promise(function(resolve, reject) {

        db.query(string)
            .on('result', resolve)
            //i supposed an error event exist
            .on('error', reject);

    })
}

//and now the usage
function help() {

    //basic method
    //first query calling
    query('your query string')
        .then(function(result) {
            //behaviour

            //second query calling, the result will send to the next 'then' statement
            return query('second query');
        })
        .then(function() {
            //behaviour


            //at this point, all queries are finished
            callback() ;
        });
}

//parallelized sample

function help() {

    //starts all queries and trigger the then if all succeeds
    Promise.all([query('your query string'), query('second query')])
        .then(function(results/*array of results*/) {
            //behaviour

            callback();
        })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM