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 (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
getEventsFeedfunction makes an asynchronous AJAX call and callscallbackwhen the server replies. In other words, the callback function is run some time after the rest of the code.Therefore, the outer
alertis 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:
You would call this function the same way you call
getEventsFeed.For example: