我有一个函数,我想在另一个函数中调用它以获取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

}

最佳答案

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

08-06 07:13
查看更多