gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:49:30 25 4
gpt4 key购买 nike

我在下面有一个 phonegap 数据库功能 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;
}

最佳答案

我将假设 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
});

关于javascript - 在 Phonegap DB 函数中返回函数外部的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19147262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com