0

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?

Tom
  • 69
  • 2
  • 8
  • 1
    Take a look at [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all). Does your database support returning `Promise`s instead of using a callback? – qxz Dec 05 '16 at 07:10
  • http://stackoverflow.com/questions/6597493/synchronous-database-queries-with-node-js – Adiii Dec 05 '16 at 07:13

2 Answers2

0

the best way to complete your requirement use async.

var name = ["shekhar", 'vishal', "param", "abhishek", 'amit'];
    for (var i = 0; i < 5; i++) {
        var item = name[i];//execute your first loop here
    }
    async.eachSeries(name, processData, function (err) {
        if (err) {
            res.json({status: 0, msg: "OOPS! How is this possible?"});
        }
        res.json("Series Processing Done");
    })
    function processData(item, callback) {
//execute your second loop here
        });
Shekhar Tyagi
  • 1,644
  • 13
  • 18
  • Got it, thank you! I've learned another way for synchronization besides promise from your answer! – Tom Dec 06 '16 at 04:44
0

Using promises, the asynchronous block of code should return a promise.

The database read function should return a promise, and can easily be rewritten as

function readFromDatabase(i){
    return new Promise(function(resolve, reject){
        db.read(i, function(rs) {   // read data from database and put it into array
            resolve(rs);
        }
    });
}

You then run your loop and get all the values from the database, await the promises and access the result in the .then() function where you can iterate of them.

//We create an empty array to store our promises
var arrayOfPromises = [];
for (var i = 0; i < 10; i++) {
    //We push each promise to the array
    arrayOfPromises.push(readFromDatabase(i));
}

//We wait until all promises have
Promise.all(arrayOfPromises)
    .then(function(arrayOfResults){
        //arrayOfResults is an array with the resolved values from the 'readFromDatabase' function
    })
    .catch(function(){
        //Handle errors
    });
Daniel B
  • 8,770
  • 5
  • 43
  • 76