1

我有一个 JavaScript 类来处理对本地数据库的查询(在 WebOs 设备上)。现在我想做的是,用我所有的基本查询创建一个模型来简化我的代码。

所以首先我创建一个函数:

getLists: function(){
          this.query( 'SELECT * FROM lists ORDER BY rowID DESC', { 
                onSuccess:  enyo.bind(this,function(data) { this.getData(data); } ), 
                onError: function() { return false; } } );
   }

而且我有接收数据的回调函数:

getData: function(data){
       return data;
   }

现在我想做的是从我的应用程序中这样调用它:

var data = getLists();

问题是,这不是从我的回调函数(getData)返回数据。我的问题是如何让“getLists”从回调中返回数据?

谢谢

4

2 回答 2

2

您正在考虑帝国:C 跟随 B 跟随 A。忘记这一点。

AJAX 和现代 JavaScript 的工作方式不同。你永远不会说“立即获取数据”,而是说“当数据可用时调用 X”。

所以解决方案是编写一些对数据有用的代码。让我们调用这个函数a。代替:

var data = conn.getData();
a( data );
b( data );
c( data );

你做

conn.getData( a ); // a has to call b which calls c.

最终,数据将在那里,a并将data作为参数调用。

看?您不会像在传统编程中那样链接调用a()和。b()相反,您创建的函数可以执行您想要的操作并传递这些函数。

于 2011-08-18T15:22:07.787 回答
1

你达不到。AJAX 中的第一个 A 是异步的。请求与其他处理“超时”发生。您的调用getLists在它启动 AJAX 请求后返回,并且在远程服务器响应 AJAX 请求时调用回调函数。

-- 编辑评论 --

如果你想“观察”一个变量,你可以使用这样的东西:

// Set up a container for the data to return to.
var retData;

// Modify the getData function to assign to the global variable
getData: function (data) {
  retData = data;
}

// Start the "wait" process.
var myInterval = setInterval(function () {
  if (retData == undefined) {
    return;
  }

  // when the return data shows up stop waiting.
  clearInterval(myInterval);

  // some other data processing here in this function
  // or trigger the actual processing function.
  // don't have to pass retData to it, it's global, the 
  // data handler function can retrieve it itself.
  myDataHandler();
}, 1000);

// make the ajax call here.
getLists();
于 2011-08-18T15:08:10.223 回答