回调、返回值和 HTML5 executeSql 函数 [英] Callback, return value and HTML5 executeSql function

查看:28
本文介绍了回调、返回值和 HTML5 executeSql 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大问题.我知道这是关于回调,关闭,但我不知道如何解决问题.这是我的代码

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

我知道executeSql是异步函数,但是不知道executeSql的结果如何保存和返回.我使用 javascript mvc 和 HTML 离线数据库.

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.

感谢您的帮助

推荐答案

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:

$.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']
                            }
                        }

                        success(result); //toss the result into the 'success' callback
                    })
                })
                //here result is undefined
                alert(result)
                return result
    }
})

Article.findAll([], function(view) {
        //...
    }, function() {
        //error occured
    });

这篇关于回调、返回值和 HTML5 executeSql 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆