我尝试找到类似" Promices"的解决方案。或类似"同步"或者"同步",但我不赞成正确的解决方案):
我喜欢的方式有10个桌子'用户','数据','游戏'。功能如:
getUsers(){} // UserTable
getData(){} // DataModel
getGames(){} // GameTable
getUserByGames(){} // UserModel
有些功能需要给我一个模型或表格...在某些情况下我需要那个模型或那个“回答”#39;做另一个查询和其他东西。
所以,我需要做同步查询,以最好的方式做到这一点,没有用。'然后'或类似的东西:/
你知道我怎么能在nodejs做什么吗?
(也许一个解决方案可以在每个异步函数中放置一个标志,并在回调中将标志更改为false。有一段时间for dosent结束原始函数?)
答案 0 :(得分:1)
您可以使用SynJS混合回调,顺序和并行执行,循环,递归。这是一个例子来说明:
var SynJS = require('synjs');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'tracker',
password : 'tracker123',
database : 'tracker'
});
function runSQLQuery(modules,connection,context,query,queryParams) {
var res = {done: false};
connection.query(query,queryParams, function(err, rows, fields) {
res.err = err;
res.rows = rows;
res.done = true;
//console.log('got rows:',rows);
modules.SynJS.resume(context);
});
return res;
}
function myFunc(modules,connection) {
for(var i=0; i<3; i++) {
console.log('Iteration:',i);
// sequential execution
var res1 = modules.runSQLQuery(modules,connection,_synjsContext,"SELECT 100+? as id",[i]);
SynJS.wait(res1.done);
console.log("res1=", res1.rows);
var res2 = modules.runSQLQuery(modules,connection,_synjsContext,"SELECT 200+? as id",[i]);
SynJS.wait(res2.done);
console.log("res2=", res2.rows);
// parallel execution
var res3 = modules.runSQLQuery(modules,connection,_synjsContext,"SELECT 300+? as id",[i]);
var res4 = modules.runSQLQuery(modules,connection,_synjsContext,"SELECT 400+? as id",[i]);
SynJS.wait(res3.done && res4.done);
console.log("res3,4=", res3.rows, res4.rows);
}
};
var modules = {
SynJS: SynJS,
mysql: mysql,
runSQLQuery: runSQLQuery,
};
SynJS.run(myFunc,null,modules,connection,function () {
console.log('done');
connection.end();
});
它产生以下输出:
Iteration: 0
res1= [ { id: 100 } ]
res2= [ { id: 200 } ]
res3,4= [ { id: 300 } ] [ { id: 400 } ]
Iteration: 1
res1= [ { id: 101 } ]
res2= [ { id: 201 } ]
res3,4= [ { id: 301 } ] [ { id: 401 } ]
Iteration: 2
res1= [ { id: 102 } ]
res2= [ { id: 202 } ]
res3,4= [ { id: 302 } ] [ { id: 402 } ]
done