1

我在使用以下 javascript 代码时遇到了一些问题。

        var returnValue = false;
        function hasItem(id) {
            //I want this entire function to run first
            db.transaction(function(tx) {
                tx.executeSql("SELECT * FROM library WHERE id == "+id,[],function(tx, results) {
                    returnvalue = results.rows.length>0; 

                },errorCB);
            },errorCB,successCB);

            //then this
            return returnvalue;
        }

但是 sql 函数似乎在一个单独的线程中运行,使函数一直返回 false .. 有没有办法“强制等待”..?

4

1 回答 1

3

有什么办法“强制等待”..?

不,你必须做的是改变你的hasItem函数,让它接受一个提供信息的回调,而不是返回一个值。

不知道你errorCBsuccessCB回调做什么有点棘手,但有一些类似的东西:

function hasItem(id, callback) {
    var returnValue = false;
    db.transaction(function(tx) {
        tx.executeSql("SELECT * FROM library WHERE id == "+id,[],function(tx, results) {
            returnValue = results.rows.length > 0; 
        },failed);
    },failed,function() {
        successCB();
        callback(returnValue);
    });

    function failed() {
        errorCB();
        callback(null); // Or whatever you want to use to send back the failure
    }
}

然后,而不是这个

if (hasItem("foo")) {
    // Do something knowing it has the item
}
else {
    // Do something knowing it doesn't have the item
}

你像这样使用它:

hasItem("foo", function(flag) {
    if (flag) {
        // Do something knowing it has the item
    }
    else {
        // Do something knowing it doesn't have the item
        // (or the call failed)
    }
});

如果你想在回调中告诉调用是否失败

hasItem("foo", function(flag) {
    if (flag === null) {
        // The call failed
    }
    else if (flag) {
        // Do something knowing it has the item
    }
    else {
        // Do something knowing it doesn't have the item
    }
});
于 2013-02-25T09:37:17.353 回答