多个查询的节点MySql回调

yan*_*234 2 javascript mysql callback node.js

在尝试创建将行添加到在MySql数据库上创建的新表的逻辑时,我遇到了一个问题。添加行时,我需要查询数据库4次以检查其他行,然后将正确的值添加到新行。我正在使用node.js和mysql模块来完成此任务。当我遇到麻烦时,代码不会在插入新行之前等待4个查询完成,因此每次将被发现的值设置为0。经过一些研究,我意识到回调函数应该是正确的,看起来像这样:

var n = 0;
connection.query("select...", function(err, rows){
    if(err) throw err;
    else{
        if(rows.length === 1) ++n;
    }
    callback();
});

function callback(){
    connection.query("insert...", function(err){
         if(err) throw err;
    });
}
Run Code Online (Sandbox Code Playgroud)

注意:select查询只能返回一项,因此if条件不应影响此问题。

我只想知道只有一个查询要等待的回调函数,但是对于多个查询要等待我有点迷茫。我唯一的想法是创建另一个变量,该变量在调用回调之前递增,然后在回调函数的参数中传递。然后在回调内部,查询可以用if语句封装,条件是该变量等于需要调用的查询数量,此处我将其设为4。我可以看到它正在工作,但是不确定这种情况是否已经内置了解决方案,或者是否已经开发了其他更好的解决方案。

Gep*_*ser 5

您需要asynchttps://github.com/caolan/async)。您可以使用此模块执行非常复杂的逻辑。

var data = {} //You can do this in many ways but one way is defining a global object so you can add things to this object and every function can see it

firstQueryFunction(callback){
    //do your stuff with mysql
    data.stuff = rows[0].stuff; //you can store stuff inside your data object
    callback(null); 
}

secondQueryFunction(callback){
    //do your stuff with mysql
    callback(null);
}

thirdQueryFunction(callback){
    //do your stuff with mysql
    callback(null);
}

fourthQueryFunction(callback){
    //do your stuff with mysql
    callback(null);
}

//This functions will be executed at the same time
async.parallel([
    firstQueryFunction,
    secondQueryFunction,
    thirdQueryFunction,
    fourthQueryFunction
], function (err, result) {
     //This code will be executed after all previous queries are done (the order doesn't matter).
     //For example you can do another query that depends of the result of all the previous queries.
});
Run Code Online (Sandbox Code Playgroud)