samedi 27 juin 2015

node.js synchronous call gather results

I have a table where Persons are saved an their time (in seconds) where they were active. I would like to write a function that gathers the total time in another table called gather.

For each row I am checking if an entry in the gather table exists. Depending on that result I make an insert or an update.

db.serialize(function() {
    db.each("SELECT * from TEST", function(err, row) {
        db.get("SELECT * from GATHER where name = " + row.name "", function(err, row) {
            if(row === undefined || row === null){
                var stmt = db.prepare("INSTER INTO gather (name, time) VALUE(?,?)");
                stmt.run([name, seconds], function(error){
                    console.log('lastInsert ' + this.lastID);
                }); 
                stmt.finalize();
            }else{
                seconds += row.time;//increment time
                var stmt = db.prepare("UPDATE gather SET time = ? WHERE name = ?");
                stmt.run([seconds, row.name], function(error){
                    console.log('lastInsert ' + row.idProcessed);
                }); 
                stmt.finalize();
            }
        });
    });
});

The problem that I ecounter is that sqlite runs asynchronously. Therefore multiple entries are created in my gather table although lines should be updated.

What would be the right way to run this function sychronously? Should I limit the lines and call the function every second or is there a smarted way?

Aucun commentaire:

Enregistrer un commentaire