gpt4 book ai didi

mysql - 如何从 Node.js 中运行 Mysql Select 的函数返回值

转载 作者:行者123 更新时间:2023-11-29 08:01:51 25 4
gpt4 key购买 nike

我正在运行一个简单的程序进行长轮询,以检查数据库中是否发生任何更改,并将其发送到 Node.js 中的浏览器。我知道如何使用回调函数,但我需要从 program.query 函数返回一个值,因为我将在递归函数中使用它。感谢您的帮助。

var server=http.createServer(function(req,res){
program.run(res, 5);
});

server.on('listening',function(){
console.log('ok, server is running');
});

server.listen(9000);


var program = {

run: function(res, id, old){

if(old == undefined){
// I need a value from database to be returned to old variable
old = program.query(res, id /*, function(){res.end('there') }*/);
}

clearTimeout(tt);
var tt = setTimeout( function(){

// I need a value from database to be returned to new_ variable
var new_ = program.query(res, id /*, function(){res.end('there') }*/);

if(new_ != old){
// ... Send Response with the change to browser
}
else{ // no change in database, so run again
old = new_;
program.run(res, id, old);
}

}, 2000);

},

query: function(res, id /*,callback*/){

connection.query('SELECT table1.column1 FROM table1 WHERE table1.id ="'+id+'"', function(err, rows, fields){


//callback(res,id,rows[0].column1); // I don't want this solution
return rows[0].column1; // Not working..

});


}

};

最佳答案

只需在回调中递归调用即可。它看起来和听起来一样:

var program = {

run: function(res, id, old){

if(old == undefined){
program.query(res, id , function(res,id,result){
old = result;

clearTimeout(tt);
var tt = setTimeout( function(){
program.query(res, id , function(res,id,new_){
if(new_ != old){
// ... Send Response with the change to browser
}
else{ // no change in database, so run again
old = new_;
program.run(res, id, old);
}
// not sure where you want to put the res.end()
// since I don't really know your logic.
});

}, 2000);
});
}
else {
// This code is of course identical to the code above
// so you can refactor it out into its own function.

clearTimeout(tt);
var tt = setTimeout( function(){
program.query(res, id , function(res,id,new_){
if(new_ != old){
// ... Send Response with the change to browser
}
else{ // no change in database, so run again
old = new_;
program.run(res, id, old);
}
// not sure where you want to put the res.end()
// since I don't really know your logic.
});

}, 2000);
}
},

query: function(res, id, callback){

connection.query('SELECT table1.column1 FROM table1 WHERE table1.id ="'+id+'"', function(err, rows, fields){


callback(res,id,rows[0].column1);
});


}

};

关于mysql - 如何从 Node.js 中运行 Mysql Select 的函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621183/

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