Return value from Ajax callback?
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
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:
var data = conn.getData();
a( data );
b( data );
c( data );
you do
conn.getData( a ); // a has to call b which calls c.
Eventually, the data will be there and a
will be called with data
as an argument.
See? You don't chain calls to a()
and b()
as in traditional programming. Instead, you create functions that do what you want and pass those functions around.
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:
// 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();
精彩评论