回调、返回值和 HTML5executeSql 函数
我有一个大问题。我知道这是关于回调、关闭,但我不知道如何解决问题。这是我的代码
$.Model.extend('Article',
{
findAll : function(params, success, error){
var result = []
db.transaction(function(tx) {
tx.executeSql('select * from contents', [],function(tx, rs) {
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
id: row['id'],
title: row['title'],
body: row['body']
}
}
})
})
//here result is undefined
alert(result)
return result
}
})
//undefined
var view = Article.findAll
我知道executeSql是异步函数,但我不知道如何保存和返回executeSql的结果。我使用 javascript mvc 和 HTML 离线数据库。
感谢您的帮助
I have a big problem. I know it's about callback, closure but I don't know how to solve the problem. Here is my code
$.Model.extend('Article',
{
findAll : function(params, success, error){
var result = []
db.transaction(function(tx) {
tx.executeSql('select * from contents', [],function(tx, rs) {
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
id: row['id'],
title: row['title'],
body: row['body']
}
}
})
})
//here result is undefined
alert(result)
return result
}
})
//undefined
var view = Article.findAll
I know that executeSql is asynchronous function, but I don't know how to save and return result of executeSql. I use javascript mvc and HTML offline database.
Thank you for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
W3C Web 数据库规范讨论了对异步和同步数据库操作的支持。 (参见 4.3 和 4.4)
如果您无法使用同步实现,那么您可能需要考虑像这样解决问题:
The W3C web database spec talks about support for both Asynchronous and Synchronous database operations. (See 4.3 and 4.4)
If you can't use a synchronous implementation, then you might want to consider approaching the problem like this instead:
我有同样的问题,但你可能想使用这个小包装库,让生活更轻松;)
http:// github.com/grosser/arjs
I have the same issues, but you might want to use this little wrapper library that makes life easier ;)
http://github.com/grosser/arjs
我也遇到了同样的问题,尤其是在移动开发项目上。我创建了一个库,消除了回调的需要:
http://code.google.com/p/proto-q/
这个使我的代码更容易排除故障、维护和增强。
我添加了对 AJAX、Web Worker、脚本注入和存储 API 的支持。我希望它有帮助。
I had the same problem, especially on mobile development projects. I created a library that eliminates the need for callbacks:
http://code.google.com/p/proto-q/
This made my code easier to troubleshoot, maintain, and enhance.
I added support for AJAX, web workers, script injection, and the storage APIs. I hope it helps.
您尝试同步使用结果,这是您在定义之前的访问结果(实际上在您的代码示例中,它不是未定义的,它是一个空数组),尽管我希望这是因为您已将声明从其原始位置移动,试图找出什么正在发生。
尝试这个修改后的示例:-
Article.findAll() 现在是一个异步函数,其回调(闭包)接收结果。
Your trying to use the result synchronously, that is your accessing result before its defined (actually in your code example its not undefined, its an empty array) though I expect thats because you had moved the declaration from its original position trying to figure out what was happening.
Try this modified example:-
Article.findAll() is now an asynchronous function, and its callback (closure) receives the results.