Node.js NodeJS范围问题
处理此路由时,我正在尝试访问“std”阵列:Node.js NodeJS范围问题,node.js,Node.js,处理此路由时,我正在尝试访问“std”阵列: var std; ...... ...... // here I fill std with some data ...... 我注意到,一旦执行流进入connection.connect块,就会触发该问题,这是一个范围问题;我到处寻找答案,但找不到解决我具体问题的办法。 我怎样才能做到这一点 connection.connect的执行被延迟,因此当它触发i时,它的值与for循环向它传递对i的引用时的值不同。因此,要在该特定循环执行中锁定i的值,请
var std;
......
...... // here I fill std with some data
......
我注意到,一旦执行流进入connection.connect块,就会触发该问题,这是一个范围问题;我到处寻找答案,但找不到解决我具体问题的办法。
我怎样才能做到这一点 connection.connect的执行被延迟,因此当它触发
i
时,它的值与for
循环向它传递对i
的引用时的值不同。因此,要在该特定循环执行中锁定i
的值,请将连接.connect
方法和回调包装在IIFE中,并将i
作为参数传递:
if(error)
{
console.log('Unable to connect to database.');
}
else
{
console.log("i= " + i);
console.log("I'm in : hr_cours = " + std[i].hr_cours);
connection.query("INSERT INTO assiste VALUES (CURDATE(),(SELECT id_etud FROM Etudiant WHERE nom_etud = ?),(SELECT s.id_seanceFROM Seance s, aura_lieu a, jour j, fait_objet fWHERE s.id_seance = a.id_seanceAND CURTIME() BETWEEN a.heure_debut AND a.heure_fin AND a.id_jour = j.id_jour AND j.dat = CURDATE() AND f.id_seance = s.id_seance AND f.id_ens = ?), ?)", [std[i].nom_etud, idEns, std[i].hr_cours], function(er1, res1){
if(er1)
{
console.log('Query error: ');
}
else
{
console.log('success');
}
});
}
});
}
}
res.end("all");
}
});
});
关于IIFE和范围关闭的更详细解释,请参见我的回答:
还有一个JSFIDLE游乐场来探索这项技术:。这是你的问题:
~function(i) {
connection.connect(function(error){
console.log('after hr_cours = ' + std[i].hr_cours);
// other stuff
})
}(i)
另一种解决方案:forEach
loop,它已经有了回调函数
for (var i = 0; i < std.length; i++) (function(i){
connection.connect(function(error) {
// ...
// Here, since i is an argument passed to outer function
// i will be i,2,3...
})(i);
你可以考虑用<代码>节点-<代码>来启动节点,使用“让”代替“var”:我做了…但同样的老错误可能是@DeveloperX的重复-请对您认为有用的两个回答进行投票,并请“接受”其中一个。
~function(i) {
connection.connect(function(error){
console.log('after hr_cours = ' + std[i].hr_cours);
// other stuff
})
}(i)
app.post('/saveABS', function(req, res) {
// ...
for (var i = 0; i < std.length; i++) {
// ...
// This is SYNC. Here i = 0,1,2...
connection.connect(function(error) {
// This is A-SYNC.
// Here i = std.length + 1
// always!
// No matter even if it syntactically looks like i should be 1,2,3 according to the loop
// but all of this is executed way after the loop has long been completed
// ...
// Here it displays undefined.
console.log('after hr_cours = ' + std[i].hr_cours); // <============ undefined
for (var i = 0; i < std.length; i++) (function(i){
connection.connect(function(error) {
// ...
// Here, since i is an argument passed to outer function
// i will be i,2,3...
})(i);
std.forEach(function(currentValue, i, std){
connection.connect(function(error) {
// ...
// Same here, since i is an argument passed to outer function
// i will be i,2,3...
// Also currentValue = std[i] so you can use that
});