Reputation: 117
var links = [];
function getFeed() {
$.getJSON("http://www.reddit.com/.json?jsonp=?", function (data) {
$.each(data.data.children, function (i, item) {
var url = item.data.url;
links.push(url);
});
alert("Inside request: " + links.length);
});
}
getFeed();
alert("Outside request: " + links.length);
Result:
Outside request: 0
Inside request: 25
Since the request seems to be asynchronous, how can I revise my code to use the data from the requests synchronously?
I apologize if I'm missing something obvious here...
Upvotes: 1
Views: 1230
Reputation: 298532
Since it's a JSONP request, you can't really do that. JSONP requests are made by creating <script>
tags that execute a global callback function with the JSON as an argument. They're not regular AJAX requests, but jQuery makes them look like that.
It'll be easier to just use callbacks:
function getFeed() {
return $.getJSON("http://www.reddit.com/.json?jsonp=?").pipe(function(data) {
return $.map(data.data.children, function(item) {
return item.data.url;
});
});
}
getFeed().done(function(links) {
console.log(links)
});
Upvotes: 1
Reputation: 55792
Because AJAX is asynchronous the alert
in your above code is going to get fired immediately after getFeed
has finished executing.
The thing is, getFeed doesn't wait for $.getJSON to return a response to finish executing, it sets up the AJAX request, sends it off, and finishes executing immediately and it's highly unlikely that by that time, the server has responded to the $.getJSON request.
This is why we use callbacks (look at the function declaration in your $.getJSON call) in asynchronous programming - we can't be 100% sure when the response is done, but we can attach a callback so that whenever the response is done, we can then perform the necessary operations.
In short, you need to place things that depend on your response to execute either in your callback, or dependent on your callback firing.
Upvotes: 1
Reputation: 3255
Add a callback to getFeed().
var links = [];
function getFeed(callback) {
$.getJSON("http://www.reddit.com/.json?jsonp=?", function (data) {
$.each(data.data.children, function (i, item) {
var url = item.data.url;
links.push(url);
});
alert("Inside request: " + links.length);
callback();
});
}
getFeed(function(){
alert("Outside request: " + links.length);
);
Upvotes: 1
Reputation: 613
getJSON
is an asynchronous function. The only reliable way to access the data is inside the function scope. Whatever you need to do with links
can be done inside the function, right?
Upvotes: 1