在Phonegap DB函数中返回函数外部的变量

时间:2013-10-02 21:37:09

标签: javascript jquery html sqlite cordova

我在下面有一个phonegap db功能JS脚本。我想在整个函数之外返回最后的字符串变量“feeds”。这只返回“未定义”。请帮助我进行必要的更改以返回“feeds”变量。

function getProviders() {
    var feeds = "";
    var db = window.openDatabase("db", "1.0", "desc", 1000000);

    db.transaction(function(tx) {
        var db = window.openDatabase("db", "1.0", "desc", 1000000);
        tx.executeSql("SELECT * FROM `feed_provider`", [], function(tx, results) {
            var len = results.rows.length;

            for (var i = 0; i < len; i++) {
                feeds += results.rows.item(i).id + "|" + results.rows.item(i).name + "|" + results.rows.item(i).status + "|" + results.rows.item(i).feed_url + ",";
            }
        }, sqlerror);
    }, sqlerror2);
    return feeds;
}

1 个答案:

答案 0 :(得分:5)

我假设db.transactiontx.executeSql是异步的,在这种情况下我会使用deferred

function getProviders() {
    var feeds = "";
    var def = $.Deferred();
    var db = window.openDatabase("db", "1.0", "desc", 1000000);

    db.transaction(function(tx) {
        var db = window.openDatabase("db", "1.0", "desc", 1000000);
        tx.executeSql("SELECT * FROM `feed_provider`", [], function(tx, results) {
            var len = results.rows.length;

            for (var i = 0; i < len; i++) {
                feeds += results.rows.item(i).id + "|" + results.rows.item(i).name + "|" + results.rows.item(i).status + "|" + results.rows.item(i).feed_url + ",";
            }
            def.resolve(feeds);
        }, sqlerror);
    }, sqlerror2);
    return def.promise();
}

这样称呼:

getProviders().done(function(feeds) { 
    // do something with feeds
});