0

我定义了以下 Javascript 函数:

function RecoverDataFromTable(table_name) {
              query = "";

              //some code that build a query string from table_name and
              //other arguments given to the function

              function Query(database) {
              database.executeSql(query, [], RecoverResults, Error)
              }

              function RecoverResults(database, results) {
              var my_result = results.rows(0).id;
              // assume this works and store a value to my_result
              }

              function Error(error) {
              //alert something
              }

              function Success() {
              //alert something
              }

              database.transaction(Query, Error, Success)                 

              }

现在,我怎样才能返回 my_result 值以便我可以做到这一点?

var my_var = RecoverDataFromTable(table_name, argument1, argument2.....)

提前致谢。询问您是否需要更多解释。:)

http://www.raymondcamden.com/index.cfm/2012/1/6/Working-with-dates-and-SQLite-in-PhoneGap

4

3 回答 3

1

你不能真的像那样设置变量,因为函数是异步的。相反,您应该在对RecoverDataFromTable的请求中包含一个回调函数。像这样定义它:

function RecoverDataFromTable(callback, table_name) {
     ...

     function RecoverResults(database, results) {
          var my_result = results.rows(0).id;
          // assume this works and store a value to my_result
          // make the callback:
          callback(result);
     }
     ...
}

然后像这样拨打电话:

function handleResult(my_result)
{
    // handle the result here
}

RecoverDataFromTable(handleResult, table_name, argument1, argument2.....);
于 2012-04-24T08:06:46.090 回答
0

如果您的功能 RecoverResults 是异步的,那么您可以使用::

function RecoverDataFromTable(callback, table_name) {
      ...
      function RecoverResults(callback, database, results) {
          var my_result = results.rows(0).id;
          callback(my_result);
          // assume this works and store a value to my_result
      }
}
RecoverDataFromTable(function(result) {
    var my_var = result;

}, table_name, argument1, argument2.....);
于 2012-04-24T07:52:53.997 回答
0

不是吗?

function RecoverResults(database, results) {
 return results.rows(0).id;
}

var my_result = RecoverResults();
于 2012-04-24T07:56:53.087 回答