0

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));
CJ Johnson
  • 1,081
  • 9
  • 13
  • `table[i].genre` will only have data when its related `apiCall` is execute to `success` callback, you have create a list to check if all the Media is loaded, and call that `init` when all loaded. – fuyushimoya Jul 06 '15 at 17:22
  • You are trying to access the properties before the Ajax response was received. – Felix Kling Jul 06 '15 at 17:22
  • I see you're trying to use a `callback` in that `makeMovieObjects` function, but that's not enough - you have to call it back at the right time, when all responses are received. – Bergi Jul 06 '15 at 17:24
  • `makeMovieObjects` calls the given `callback` function *immediately* after creating the `Media` objects. At that moment, the asynchronous requests started by `apiCall` have not completed yet. The reason why you *do* see those properties in the console is because `console.log(table[i])` logs the object *reference* to the console (as opposed to a 'snapshot' of all its properties). By the time you inspect the logged object in the browser's console, it will have those extra properties set. – Mattias Buelens Jul 06 '15 at 17:24

0 Answers0