1

I have a function and i want to call it in a other function to get the API key. If i do this i the return value is undefined.

How can i solve this?

function getApiKey(callback) {

    var db = app.db;

    db.transaction(
        function (tx) {
            tx.executeSql("SELECT api_key FROM settings WHERE id='1'", [], function (tx, result) {
                var apiKey = result.rows.item(0).api_key;

                alert(apiKey); // here it works

                return apiKey;

            });
        }
    );
}

function getData() {

    var myKey = getApiKey();

    alert(myKey); // undefined

}
Leon van der Veen
  • 1,652
  • 11
  • 42
  • 60

2 Answers2

3

You have a callback being passed as a param, use it! You can't return from async calls!

function getApiKey(callback) {
    var db = app.db;
    db.transaction(function (tx) {
        tx.executeSql("SELECT api_key FROM settings WHERE id='1'", [], function (tx, result) {
            var apiKey = result.rows.item(0).api_key;
            callback(apiKey);
        });
    });
}

function getData() {
    getApiKey(function(key) {
        var myKey = key;

        /* Any logic with myKey should be done in this block */
    });
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Thanks for the response. Getting there. But if i do a - alert(myKey); - in the getData function it only works if i do that in the the getApiKey. Not if i do that after that. – Leon van der Veen Aug 19 '15 at 14:44
  • @LeonvanderVeen -- Yeah - that's the nature of async. You need to do your logic in the callbacks. – tymeJV Aug 19 '15 at 14:47
-3

why don't you create a local variable inside the getApiKey function and assign apiKey to it.

function getApiKey(callback) {
     var returnApiKey = "";
     var db = app.db;

     db.transaction(
         function (tx) {
            tx.executeSql("SELECT api_key FROM settings WHERE id='1'", [],        function (tx, result) {
                        var apiKey = result.rows.item(0).api_key;

                        alert(apiKey); // here it works

                        returnApiKey = apiKey;

                    });
                });
  return returnApiKey;
}


function getData() {

   var myKey = getApiKey();

   alert(myKey); // undefined

}
Venkata K. C. Tata
  • 5,539
  • 4
  • 22
  • 35