Javascript函数在其他函数中返回undefined

时间:2015-08-19 14:27:13

标签: javascript function cordova

我有一个函数,我想在其他函数中调用它来获取API密钥。如果我这样做,我的返回值是未定义的。

我该如何解决这个问题?

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

}

2 个答案:

答案 0 :(得分:3)

你有callback作为参数传递,使用它!你不能return来自异步电话!

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

答案 1 :(得分:-3)

为什么不在getApiKey函数中创建局部变量并为其分配apiKey。

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

}