2013-02-25 26 views
1

我遇到一些麻烦,下面的JavaScript代码..如何确保函数a已经在函数b ..之前运行?

 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所有的时间..有什么办法“迫使等待“..?

+0

检查此链接:http://stackoverflow.com/questions/1898178/callback-return-value-and-html5-executesql-function – Simon 2013-02-25 09:43:05

回答

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 
    } 
}); 
+0

的'db.transaction'已经似乎有成功/错误回调,OP应该使用这些。 – Dunhamzzz 2013-02-25 09:40:11

+0

@Dunhamzzz:是的,很难说这些可能会做什么,但我怀疑它们可能相当通用。我添加了一些与它们交互的示例代码。 – 2013-02-25 09:42:17

+0

谢谢,漂亮! :-) – 2013-02-25 09:44:35

相关问题