gpt4 book ai didi

javascript - 多个查询的 Node MySql 回调

转载 作者:行者123 更新时间:2023-11-29 01:16:21 26 4
gpt4 key购买 nike

我在尝试创建逻辑以将行添加到我在 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;
});
}

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

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

最佳答案

您需要async ( https://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.
});

关于javascript - 多个查询的 Node MySql 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31530431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com