1

我在下面有一个 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;
}
4

1 回答 1

5

我将假设db.transaction或者tx.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
});
于 2013-10-02T21:46:09.507 回答