Abdullah Gheith
Abdullah Gheith

Reputation: 520

Code doesn't execute correctly the first time. Next time it does

I made some code to check if a value in the database is null or not.

Here is my code:

var tabel;
var running = false;
function CheckRunning(tabel){
this.tabel = "tabel"+tabel+"";
var db = window.openDatabase(this.tabel, "1.0", this.tabel, 1000000);
db.transaction(checkrunningDB, checkerrorCB);
console.log(this.running);
return this.running;
}

function checkrunningDB(tx) {
   tx.executeSql('SELECT max(id), sluttime FROM '+this.tabel, [], checkrunningSuccess, checkerrorCB);
}

function checkrunningSuccess(tx, results) {
    if (results.rows.item(0).sluttime != null){
        this.running = false;
    } else{
        this.running = true;
    }
}
function checkerrorCB(err) {
     this.running = false;
    console.log(err);
}

So i made a button, the runs this CheckRunning() function.

When i press it, i get this (each line represents a button click):

false
true
true 
true 
true 

Upvotes: 1

Views: 138

Answers (1)

Dennis
Dennis

Reputation: 32608

Your database functions are running asynchronously. The callback, checkrunningSuccess, will be run when it is done, but the line after db.transaction(checkrunningDB, checkerrorCB); may execute before then.

Upvotes: 3

Related Questions