如何确保函数b在函数b之前运行?

时间:2013-02-25 09:36:07

标签: javascript cordova

我在使用以下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-function似乎在一个单独的线程中运行,使得函数一直返回false ..有没有办法“强行等待”..?

1 个答案:

答案 0 :(得分: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
    }
});