简体   繁体   English

用于JavaScript数据库操作的对象方法内的异步回调

[英]asynchronous callback within a object method for javascript database operations

I would like to encapsulate SQLite database commands in a 'DBManager' class. 我想将SQLite数据库命令封装在“ DBManager”类中。 To read the data, I've written the following lines: 为了读取数据,我编写了以下几行:

DBManager.prototype.readMyData = function(param1, param2) {
this.db.transaction(function(tx) {
    tx.executeSql("SELECT * FROM myTable WHERE param1 <= ?",
    [param1],
    function(tx, result) {
      var myData = [];
      for (var i=0; i<result.rows.length; i++) {
                var row = result.rows.item(i);
                myData.push(row);
              }
    },
    errorHandler);
});
    return myData;

} }

The Problem: If I call the method readMyData() the return command is executed before the transaction method and its inner stuff. 问题:如果我调用方法readMyData(),则返回命令将在事务方法及其内部内容之前执行。

How can I handle it so that the return value of readMyData() isn't empty but holds the myData array? 如何处理它,以使readMyData()的返回值不为空,但保存myData数组?

You can't, you have to provide a callback to readMyData : 您不能,您必须提供对readMyData的回调:

DBManager.prototype.readMyData = function(param1, param2, callback) {
    this.db.transaction(function(tx) {
        tx.executeSql("SELECT * FROM myTable WHERE param1 <= ?", [param1],
            function(tx, result) {
                var myData = [];
                for (var i=0; i<result.rows.length; i++) {
                    var row = result.rows.item(i);
                    myData.push(row);
                }
                callback(myData);  // <- passing the data to the callback
            },
            errorHandler);
    });
}

and then call it with: 然后调用:

db.readMyData(foo, bar, function(result) {
   // work with result here
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM