So, I am learning Javascript while playing white Google Calendar APIs and I just can't figure how this piece of code is working this way:
var entriesResult = [];
var data = new Date(2010,3,22,17,0,0);
var callback = function(result) {
var entries = result.feed.getEntries();
if (entries.length != 0) {
entriesResult = eventsManager(entries, 0, data);
window.alert("inner entriesResult " + entriesResult.length);
}
}
this.service.getEventsFeed(this.query, callback, handleGDError);
window.alert("outer entriesResult " + entriesResult.length);
eventsManager() is a function that returns an array of Objects.
getEventsFeed() it's an API function: it queries the service and pass a "feed root" (a feed with selected items) to the callback function.
Why the first alert开发者_JAVA技巧 (inner..) outputs a valid entriesResult.length while the second one (outer..) always outputs a 0?
I tought javascript arrays are always passed by reference, what's wrong whit my code? Thank you :)
The getEventsFeed
function makes an asynchronous AJAX call and calls callback
when the server replies. In other words, the callback function is run some time after the rest of the code.
Therefore, the outer alert
is executed before the callback, when the array is still empty.
EDIT
To return a value from an AJAX call, you need to accept a callback as a parameter, then call the callback once you have a value to return.
For example:
function myFunction(someParam, callback) {
//Do things...
var eventsFeedCallback = function() {
//Do more things, and figure out what to return
callback(someValue); //Call the user's original callback to give back a value
};
this.service.getEventsFeed(this.query, eventsFeedCallback , handleGDError);
//Do more things...
}
You would call this function the same way you call getEventsFeed
.
For example:
myFunction("Parameter!", function(value) {
//This is the callback, and will be called when the AJAX call finishes
//Do things with value
});
The line:
window.alert("outer entriesResult " + entriesResult.length);
is executed immediately after you start the async operation (before it completes).
the line in the callback function is executed later, after the async operation is complete.
精彩评论