Ajax回调的返回值?
我有一个 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();
问题是,这不是从我的回调函数返回数据(获取数据)。我的问题是如何让“getLists”从回调返回数据?
谢谢
I have a JavaScript class that handles queries to a local DB (on a WebOs device). Now what I want to do is, create a model with all my basic queries to simplify my code.
So first I create a function:
getLists: function(){
this.query( 'SELECT * FROM lists ORDER BY rowID DESC', {
onSuccess: enyo.bind(this,function(data) { this.getData(data); } ),
onError: function() { return false; } } );
}
And than I have my callback function which receives the data:
getData: function(data){
return data;
}
Now what I would like to do, is call it like this from my app:
var data = getLists();
The problem is, this is not returning the data from my callback function (getData). My question is how can I have "getLists" return the data from the callback?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你在想的是帝国主义:C 跟随 B 跟随 A。忘掉这一点吧。
AJAX 和现代 JavaScript 的工作方式不同。你从来不会说“立即获取数据”,你会说“当数据可用时致电 X”。
因此,解决方案是编写一些对数据执行有用操作的代码。我们将此函数称为
a
。而不是:最终
,数据将在那里,并且将使用
data
作为参数来调用a
。看?您不需要像传统编程那样链接对
a()
和b()
的调用。相反,您可以创建执行您想要的操作的函数并传递这些函数。You're thinking imperial: C follows B follows A. Forget about that.
AJAX and modern JavaScript works differently. You never say "get data now", you say "call X when data is available".
So the solution is to write some code which does something useful with the data. Let's call this function
a
. Instead of:you do
Eventually, the data will be there and
a
will be called withdata
as an argument.See? You don't chain calls to
a()
andb()
as in traditional programming. Instead, you create functions that do what you want and pass those functions around.你没机会去。 AJAX 中的第一个 A 是异步的。这些请求与其他处理“不合时宜”地发生。对
getLists
的调用在发起 AJAX 请求后返回,并且当远程服务器响应 AJAX 请求时调用回调函数。-- 编辑评论 --
如果你想“观察”一个变量,你可以使用这样的东西:
You don't get to. The first A in AJAX is Asynchronous. The requests happen "out of time" with the other processing. Your call to
getLists
returns after it launches the AJAX request, and the callback function is called when the remote server responds to the AJAX request.-- Edited for comments --
If you want to "watch" a variable you can use something like this: