Update: I read post that this one was flagged as a duplicate of. I generally get how callbacks are supposed to work. My problem is I'm calling the API in a loop that is creating objects, so I can't figure out how to put a callback in there to make the next method wait without calling that callback with each loop iteration.
I created objects and added API data to them. I use a callback so the next bit of code won't run until the API properties are available. The callback is not working.
function Media(boxCover, searchName, year) {
this.boxCover = boxCover;
this.searchName = searchName;
this.year = year;
this.genre = "";
this.imdbRating = "";
apiCall(this);
}
function makeMovieObjects(callback) {
var table = [
new Media('imgs/avengers.jpg', "Avengers", "2012"),
new Media('imgs/blade_runner.jpg', "Blade Runner", "1982")
];
callback(table);
}
function apiCall(obj){
var link = "http://www.omdbapi.com/?t=" + obj.searchName + "&y=" + obj.year + "&plot=short&r=json";
var oReq = new XMLHttpRequest();
oReq.open("get", link, true);
oReq.onload = reqListener;
oReq.send();
function reqListener() {
var apiReturn = JSON.parse(this.response);
obj.genre = apiReturn.Genre;
obj.imdbRating = apiReturn.imdbRating;
}
}
function init(table) {
for (var i = 0; i < table.length; i++) {
console.log(table[i]); // object contains all data
console.log(table[i].genre); // fails (API sourced data)
console.log(table[i].year); // success (data hard coded)
}
}
makeMovieObjects(init(table));