Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

javascript - Callback, return value and HTML5 executeSql function

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...