将variables传递给Node.JScallback函数

我很新的Node.JS,我试图build立一个应用程序,但我遇到了一些问题,我似乎无法find解决scheme。 我在Google上花了不less时间,但没有运气。

下面是一个小小的片段,说明了我正在尝试的东西。

mysql.query('SELECT * FROM leads', function(err, res){ for(x in res){ id = res[x]; mysql.query('SELECT FROM survey WHERE lead_id = ?', [id], function(x, res){ // I want to access the id variable here but since this is in a // callback the id variable could've been changed by now // AND THIS DOES'T ALWAYS RETURN SOMETHING OR I COULD'VE // JUST USED THE LEAD_ID IN THE RETURNED DATASET }); } }); 

我想在callback中访问这个idvariables,但是由于节点的asynchronous特性,variables会在第一个callback被返回之前执行for循环结束后发生改变。

我的问题是你可以传递给callback函数的variables? 或者有人可以帮助我另一个解决scheme。

提前致谢!

艾哈迈德

而不是使用for循环使用Array.forEach,通过这样做,您可以创build一个封闭的idvariables被捕获

 mysql.query('SELECT * FROM leads', function(err, res){ res.forEach(function(x) { var id = x; //Captured in the closure of the mysql.query below mysql.query('SELECT FROM survey WHERE lead_id = ?', [id], function(x, res){ //Do stuff with id }); } });