I am confused why in the code below the first console.log shows me the object, yet the second is undefined. How do I fix this problem?
var listOfTweets = [];
for(var k = 0; k < search.length; k++){
$.getJSON(searchURL, function(tweets){
listOfTweets[k] = tweets;
console.log(listOfTweets[k]);
});
console.log(listOfTweets[k]);
}
The getJSON is executed asyncronous and the last console.log is there for executed before the assignment
Since I don’t know what you actually want is hard to tell you what you should do. What you need to keep in mind is the execution order.
In this code
the first thing that happens is a request being send to
searchURLthen next thing is that “Request send” will be printed to the console and when the browser receives the response to the request then and no sooner will the function be called and “done” will be printed to the consolefurther your code has a problem with closure since k is closed over and will have the same value for all invocations of the call back (1)
to get around that problem you could use a self executing function
notice that k is used as an argument for a function immediatedly, the value of the argument is stored for reference by the function return as the callback and will not change when k is incremented. If you do as you have done then since all callbacks are referencing the same object they will all also have the same value for k
(1) unless some returns before the looping ends