dimanche 8 novembre 2015

sequencial queries using nodejs and SqlLite

So still pretty new to the nodejs way of thinking and have a question on how best to do this

here is a snippet of code that works where i get two id's from the SqliteDB and then send them to the client.

client.on('join', function(data) {
    var last_new_id=0;
    var last_old_id=0;
    var db = new sqlite3.Database(file);
    db.serialize(function() {
        db.each("SELECT last_new_id, last_old_id FROM image_status ", function(err, row) {
            if ( err ){
                console.log("**** ERROR IN SELECT ****");
                console.log(err);
            }else{
                last_new_id =  row.last_new_id;
                last_old_id =  row.last_old_id;
            }
        }, function() {
            client.emit('joined', {last_new_id: last_new_id, last_old_id: last_old_id} );
        });
    });
});
db.close();

If the image_status table is empty it goes directly to client.emit

What i want to do is if last_new_id or last_old_id is zero, i want to do another query

I thought i would try something like

}, function() {
     if ( last_new_id == 0 ) {
        //query the db with
        //SELECT image_id FROM image ORDER BY image_id DESC LIMIT 1
        last_new_id = getLastID();     
     } 
     client.emit('joined', {last_new_id: last_new_id, last_old_id: last_old_id} );
});

but what happens is the client.emit is called before the getLastID select is returned.

I am unsure how to call getLastID() synchronously or is there a better way to do this?

Thanks

Aucun commentaire:

Enregistrer un commentaire