lundi 14 mars 2016

Javascript SQLite - callback variable problems

All - I've had a few posts on here recently! Having been directed to some useful guidance on callbacks earlier today I feel I'm making very slow (think glacial) progress towards understanding and scripting asynchronous code.

Problem: I want to run a SELECT query on a database, and return the results into a useable variable - in this simple example to simply display an alert.

Code:

////////////////////////////////
//  Functions
////////////////////////////////

// SQL query function
function queryRunner(input, callback) {

    // Needs to be in .transaction to work
    database.transaction(
        function( transaction ){

            // SQL Query
            transaction.executeSql(input);

        },function(err){

            console.log('errorCB: ' + err.code + '; Message: ' + err.message);

        },function( transaction, results ){

            console.log('queryRunner success!');

            // Make callback optional
            // Make sure only processes if functions included
            // i.e. ignore strings
            if(callback && typeof(callback) === 'function') { callback(results); 
            }

        }
    ); // end database.transaction

} // End queryRunner


////////////////////////////////
//  Testing
////////////////////////////////


    var databaseOptions = {
        fileName: "sqlite_WAtest",
        version: "1.0",
        displayName: "SQLite WA Test",
        maxSize: 1024
    }; // End databaseOptions



    var database = openDatabase(
        databaseOptions.fileName,
        databaseOptions.version,
        databaseOptions.displayName,
        databaseOptions.maxSize
    ); // End database

    queryRunner('DROP TABLE WORKOUTS');

    queryRunner('CREATE TABLE IF NOT EXISTS WORKOUTS (id INTEGER PRIMARY KEY AUTOINCREMENT, WOdate TEXT, WOtype TEXT);');

    queryRunner('INSERT INTO WORKOUTS (WOdate, WOtype) VALUES ("Test 1","Test 2")');

    queryRunner('INSERT INTO WORKOUTS (WOdate, WOtype) VALUES ("Test 3","Test 4")');

    queryRunner('SELECT * FROM WORKOUTS', function(){

        alert('hello');                 // Triggers fine
        alert(results.rows.item[0]);    // cannot find variable

    });

I think it's to do with the callback(results) piece - is this correct? And then is it correct to refer to an item subsequently as results.rows.item[1]? I understand this is the correct syntax, but not sure on the interaction with the callback.

I'm struggling with the connection between the query and the subsequent code - if someone could help explain I would be very grateful!

PS - I know in reality I would need to return the results variable and loop through the results to, for example, append them to a list or similar. I'm just using the alert as a 'quick and dirty' acid test on the code.

Aucun commentaire:

Enregistrer un commentaire