我在使用下面的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。有没有办法“强迫等待”?
发布于 2013-02-25 17:37:17
有没有办法“强制等待”?
不是的。您必须做的是更改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)
}
});如果您想在回调中判断调用是否失败
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
}
});https://stackoverflow.com/questions/15063898
复制相似问题