【问题标题】:How to ensure that function a has been run before function b..?如何确保函数 a 已在函数 b 之前运行?
【发布时间】:2013-02-25 09:36:07
【问题描述】:

我在使用以下 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。有没有办法“强制等待”..?

【问题讨论】:

标签: javascript cordova


【解决方案1】:

有没有办法“强制等待”..?

没有。您必须做的是更改您的 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
    }
});

【讨论】:

  • db.transaction 似乎已经有成功/错误回调,OP 应该使用这些。
  • @Dunhamzzz:是的,很难说它们会做什么,但我怀疑它们可能相当通用。我添加了一些与它们交互的示例代码。
  • @TorClaesson:不用担心,很高兴有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 2012-08-19
  • 2020-08-17
  • 2022-01-19
相关资源
最近更新 更多