1

我有以下代码:

function getRetailerName(retailerID) {
    var retailerName;
    db.transaction(function retName(qry) {
        qry.executeSql("SELECT retailerName FROM retailers WHERE token = '" + retailerID + "' ", [], function (tx, results1) {
            var len1 = results1.rows.length;
            var retailerName;
            for (var i1 = 0; i1 < len1; i1++) {
                retailerName = results1.rows.item(i1).retailerName;
                //alert(results1.rows.item(i1).retailerName);
            }
        });
        return retailerName;
    });
    alert(retName());
}

我试图从内部函数中获取值retName()并最终调用getRetailerName()以从数据库中获取值,但是它一直给我一个retName未定义的错误?

我在这里尝试了很多,

4

2 回答 2

3

你不能那样做,因为它是异步的。当您从函数返回时,查询尚未完成。相反,传递一个要执行的回调:

function getRetailerName(retailerID, callback) {
    var retailerName;
    db.transaction(function retName(qry) {
        qry.executeSql("SELECT retailerName FROM retailers WHERE token = '" + retailerID + "' ", [], function (tx, results1) {
            var len1 = results1.rows.length;
            var retailerName;
            for (var i1 = 0; i1 < len1; i1++) {
                retailerName = results1.rows.item(i1).retailerName;
                callback(retailerName);
            }
        });
    });
}

getRetailerName(1, function(name) {
    alert(name);
});
于 2013-02-27T11:30:02.747 回答
1

您不能(因为retName命名函数表达式仅在其中可用)并且您不应该尝试这样做(因为函数是异步的并且它不起作用)。相反,使用回调:

function getRetailerName(retailerID, callback) {
    var retailerName;
    db.transaction(function retName(qry) {
        qry.executeSql("SELECT retailerName FROM retailers WHERE token = '" + retailerID + "' ", [], function (tx, results1) {
            var len1 = results1.rows.length;
            for (var i1 = 0; i1 < len1; i1++) {;
                callback(results1.rows.item(i1).retailerName);
            }
        });
    });
}

getRetailerName(1, alert.bind(window));
于 2013-02-27T11:31:26.337 回答