result
будет доступен во втором обратном вызове, вот так замыкает в работе JavaScript, функции имеют доступ ко всем переменным во внешних областях, в которых они были определены.
function outer() {
var foo = 1;
function inner() { // inherits the scope of outer
var bla = 2;
console.log(foo); // works!
// another function in here well inherit both the scope of inner AND outer, and so on
}
inner();
console.log(bla); // doesn't work, raises "ReferenceError: bla is not defined"
}
outer();
Теперь, говоря о проблеме, i
не будет указывать на правильное значение, оно также будет унаследовано для второго обратного вызова, но оно является ссылкой и поэтому будет иметь неправильное значение.
Исправлено создание другого замыкания:
SQL.query("select * from blah", function(result) {
for(var i = 0; i < result.length; i++) {
(function(innerResult) { // anonymous function to provide yet another scope
SQL.query("select * from blah2 where i =" + innerResult.property, function(result2) {
// innerResult has the correct value
});
})(result[i]); // pass the current result into the function
}
});
Или дополнительная функция:
function resultThingy(result) {
SQL.query("select * from blah2 where i =" + result.property, function(result2) {
// result has the correct value
});
}
SQL.query("select * from blah", function(result) {
for(var i = 0; i < result.length; i++) {
resultThingy(result[i]);
}
});