Sinan Samet
Sinan Samet

Reputation: 6742

How can I access a variable outside executeSql function

How can I access the url variable outside of the executeSql function? (commented where I want it)

function generateUrl(id, callBack){
    var db = window.openDatabase("Database", "1.0", "Marktplaats", 200000);
    db.transaction(function (tx) {

    tx.executeSql('SELECT * FROM searches, settings', [], function (tx, results) {
         var url = "http://google.nl";
    }, null);

    //I want to access the url variable here
    });
}

Upvotes: 0

Views: 606

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

What you're suggesting doesn't make sense as executeSql is asynchronous.

tx.executeSql('SELECT * FROM searches, settings', [], function (tx, results) {
     var url = "http://google.nl";
     // This is executed 2nd
}, null);

//This is executed 1st
});

Therefore at the point of your comment, it's impossible for url to have a value.

What you should be doing, is using that callBack parameter you have to pass the url back to the caller:

tx.executeSql('SELECT * FROM searches, settings', [], function (tx, results) {
     var url = "http://google.nl";
     callBack.call(this, url);
}, null);

Then you can call generateUrl as:

generateUrl(15, function(url) {
    // URL is visible now
    console.log(url);
});

Upvotes: 1

Related Questions