Javascript 如何确保函数a在函数b之前运行。。?
我在使用以下javascript代码时遇到一些问题Javascript 如何确保函数a在函数b之前运行。。?,javascript,cordova,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 =
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。。有没有办法“强迫等待”
有没有办法“强迫等待”
不可以。您必须更改hasItem
函数,使其接受提供信息的回调,而不是返回值
不知道您的errorCB
和successCB
回调会做什么有点棘手,但大致如下:
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)
}
});
如果要在回调中告知调用是否失败:
db.transaction
似乎已经有了成功/错误回调,OP应该使用它们。@Dunhamzzz:是的,很难说它们会做什么,但我怀疑它们可能相当通用。我添加了一些与它们交互的示例代码。@TorClaesson:不用担心,很高兴这有帮助!检查此链接:
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
}
});