I'm trying to read multiple data from database, put them into an array, and deal with the array. The code looks like this:
var array = [];
// first for loop
for (var i = 0; i < 10; i++) {
db.read(i, function(rs) { // read data from database and put it into array
array.push(rs);
}
}
// second for loop
for (int i = 0; i < 10; i++) {
console.log(array[i]);
}
However, this piece of code will not work because the second for loop will execute before the first loop ends. Is there any good solutions? BTW, I've used promise like this:
var array = [];
var promise = new Promise(function(resolve, reject) {
for (var i = 0; i < 10; i++) {
db.read(i, function(rs) { // read data from database and put it into array
array.push(rs);
}
}
resolve(array);
};
promise.then(function(array) {
for (int i = 0; i < 10; i++) {
console.log(array[i]);
}
};
It doesn't work either, it seems that the resolve will not wait until all the db read operations finish. So when will the resolve wait until all the previous code finish?