有什么办法“强制等待” ..?
不,你必须做的是改变你的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
}
});
检查此链接:http://stackoverflow.com/questions/1898178/callback-return-value-and-html5-executesql-function – Simon 2013-02-25 09:43:05