简体   繁体   中英

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
    });
}

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM