Callback, return value, and HTML5 executeSql function

I have a big problem. I know this about callback, close, 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 an asynchronous function, but I don’t know how to save and return the result of executeSql. I am using javascript mvc and a standalone HTML base.

thanks for the help

+4
source share
4 answers

The W3C web database specification talks about supporting both asynchronous and synchronous database operations. (see 4.3 and 4.4)

If you cannot use a synchronous implementation, then you may need to consider a problem like this:

 $.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 }); 
+5
source

I have the same problems, but you can use this small wrapper library that makes life easier;)

http://github.com/grosser/arjs

0
source

I had the same problem, especially in mobile development projects. I created a library that eliminates the need for callbacks: http://code.google.com/p/proto-q/

This simplified my code for troubleshooting, support, and improvement.

I added support for AJAX, web workers, script injection and storage APIs. Hope this helps.

0
source

Your attempt to use the result synchronously, that is, your access result until it is determined (in fact, in your example code it is not undefined, its an empty array), although I expect that this is because you moved the declaration from its original position trying to figure out what's happening.

Try this modified example: -

 $.Model.extend('Article', { findAll : function(params, success, error){ db.transaction(function(tx) { tx.executeSql('select * from contents', [], function(tx, rs) { var result = []; for(var i=0; i<rs.rows.length; i++) { var row = rs.rows.item(i) result.push({ id: row['id'], title: row['title'], body: row['body'] }); } success(result); }); }); } }); Article.findAll({}, function(result) { // process result here }); 

Article.findAll () is now an asynchronous function, and its callback (closure) gets the results.

0
source

All Articles