HTML5数据库API:同步请求 [英] HTML5 Database API : Synchronous request
问题描述
我目前在html5 iphone webapp上使用客户端数据库。
在我的代码中,我需要检查本地数据库中是否存在行:
i currently use the client side database on an html5 iphone webapp. In my code i need to check if a row is present in the local DB :
function isStarted(oDB) {
var ret = null;
oDB.query(sql,params,function(transaction,result) {
if(result.rows.length > 0 ) {
ret = true;
} else {
ret = false;
}
});
return ret;
}
不幸的是返回isStarted ()发生在回调函数之前,我总是得到一个null值。
在 W3c规范中,我们可以看到同步-database-api但我该如何使用它?
是否有一个技巧可以通过asynchronus requets获得良好的ret值?
Unfortunately the return of isStarted() occurs before the callback function and i always get a "null" value. In the W3c spec we can see an "synchronous-database-api" but how can i use it ? Is there a trick to get the good "ret" value with asynchronus requets ?
感谢您的帮助
推荐答案
要获得实现 DatabaseSync
的对象,您必须调用 openDatabaseSync(...)
而不是 openDatabase(...)
。我不知道iPhone,或者你所拥有的 oDB
对象是什么,但根据规范你只能得到 openDatabaseSync
WebWorker中的方法,而不是普通的Web浏览器窗口
。当然 XMLHttpRequest
已经证明UI线程中潜在长度的同步操作不是一个好主意。
To get an object implementing DatabaseSync
you have to call openDatabaseSync(...)
instead of openDatabase(...)
. I don't know about the iPhone, or what the oDB
object you have is, but according to spec you only get the openDatabaseSync
method in a WebWorker and not in the normal web browser window
. Certainly XMLHttpRequest
has demonstrated that potentially-length synchronous operations in the UI thread are not a good idea.
它不是可以同步运行异步代码,反之亦然。为此,您需要语言级功能,如JavaScript没有的线程或协同例程。你必须退出你的函数并将控制权返回给浏览器,以允许它执行HTTP请求或数据库查询,并回调你给它的处理函数。
It's not possible to run asynchronous code synchronously, or vice versa. To do so you'd need language-level features like threads or co-routines that JavaScript doesn't have. You have to exit your functions and return control to the browser to allow it to perform the HTTP request or database query, and call you back on the handler function you gave it.
因此,每次执行涉及数据库IO的操作时,您都必须重写代码由内而外来传递回调函数,而不是期望返回值。
So you will have to rewrite your code ‘inside-out’ to pass callback functions instead of expecting return values, every time you do something involving database IO.
function tellMeWhenIsStarted(oDB, callback) {
oDB.query(sql,params,function(transaction,result) {
callback(result.rows.length>0);
}
});
这篇关于HTML5数据库API:同步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!