Tyler Mortensen
Tyler Mortensen

Reputation: 461

For loop proceeding before SQL Transaction completes

I am having some trouble with a database application I am working on. It seems that my javascript function continues to progress before my SQL transaction is complete. Below is a very simplified version of what I am experiencing. In the actual function, I am attempting to do some work on the table before moving to the next value in the for loop. It seems to do everything in the for loop, and then complete the SQL transactions.

Here is the sample code:

function fillTables(){
    db.transaction(function (tx){
        for(var i=0; i<3; i++){
            console.log('Filling row '+i);
            tx.executeSql(
                        'INSERT INTO Numbers (Value) VALUES (?)',
                        [i],
                        function (){
                            console.log('Inserted Row');    
                        },
                        errorCB);
            console.log('moving on...');
        }
    });
}

The console log I would expect to see is would be:

Filling Row 0
Inserted Row
moving on...
Filling Row 1
Inserted Row
moving on... 
Filling Row 2
Inserted Row
moving on... 

However, I am getting:

Filling row 0 
moving on... 
Filling row 1 
moving on... 
Filling row 2 
moving on... 
Inserted Row 
Inserted Row 
Inserted Row 

Any ideas on how I can achieve the desired outcome?

Upvotes: 2

Views: 197

Answers (2)

Carlos Nu&#241;ez
Carlos Nu&#241;ez

Reputation: 470

tx.executeSql() is an asynchronous function, in which case you need to perform a recursive call once the function is completed.

function fillTables() {
    db.transaction(function (tx){
        var recursiveFunction = function (index, length) {
            if (index < length) {
                console.log('Filling row ' + index);
                tx.executeSql(
                    'INSERT INTO Numbers (Value) VALUES (?)',
                    [index],
                    function (){
                        console.log('Inserted Row');
                        console.log('moving on...');
                        recursiveFunction(++index, length);    
                    },
                    errorCB);
             }
        }

        recursiveFunction(0, 3);
    });
}

Upvotes: 0

SnareChops
SnareChops

Reputation: 13347

tx.executeSql() is an async function and is behaving appropriately. I will look for a sync method for you and edit my response.

So according to what I've read the function is async only due to HTML5 specification. Also if you were to run it synchronously somehow it would return an "invalid state" error.

Upvotes: 1

Related Questions