I have two nested database queries:
db.query(query1, function (err, rows, fields) {
if (!err) {
console.log("outer rows.length: " + rows.length);
function outer() {
for (var i = 0; i < rows.length; i++) {
console.log(i + ". outer row");
function inner() {
db.query(query2 + i + 1, function (error, r, f) {
if (!error) {
for (var j = 0; j < r.length; j++) {
console.log(j + ". inner row");
}
}
});
};
inner();
}
}
outer();
}
});
I expect the log order to be...
outer rows.length: 2
0. outer row
0. inner row
1. inner row
1. outer row
0. inner row
However I get this result:
outer rows.length: 2
0. outer row
1. outer row
0. inner row
1. inner row
0. inner row
There are two inner rows which belong to 0. outer row und one inner row which belongs to 1. outer row. This code first logs all the outer rows, then all the inner rows.
I´m looking for a way to prevent this. I think, the issue lies in the asynchronicity of the code. I have tried to fix it by putting function inner() into an immediately invoking function with the style ( function inner() { .. } )();, but this did not change anything. How can I determine that each inner row will be logged right after its corresponding outer row, just like in the first list? Any advice would be appreciated.
Aucun commentaire:
Enregistrer un commentaire