title: JavaScript/jQuery callback using Ajax
body: <p>I'm having trouble with my functions running before Ajax requests (the first to a local JSON, the second to an online resource) have finished.</p>
  
  <p>In this example I want <code>countTheMovies</code> to run at the end after my application has got all the information it needs and populated the divs. Instead it's running straight away.</p>
  
  <p>I tried to delay it using an <code>if</code> condition, but with no joy. I've also tried with callbacks, but think I must be getting those wrong (I'm assuming callbacks are the answer). I'm aware of timed delays, but because in the actual project I'm sourcing 250+ movies (and because a timed delay seems like cheating) I thought I'd ask here instead.</p>
  
  <p>Can anyone recommend JavaScript or jQuery code to fix this problem?</p>
  
  <pre><code>$(function(){
    getMovieList();
  });
  
  function getMovieList() {
    $.ajax({
      url: "movielist.json",
      type: "GET",
      dataType: "JSON",
      success: function(data) {
        for (var i = 0; i &lt; data.length; i++) {
          var title = data[i].title.toLowerCase().split(" ").join("+");
          var year = data[i].year;
          i === data.length - 1
            ? getMovieInfo(title, year, true)
            : getMovieInfo(title, year, false);
        }
      }
    });
  }
  
  function getMovieInfo(title, year, isLast) {
    $.ajax({
      url: "https://www.omdbapi.com/?t=" + title + "&amp;y=" + year + "&amp;plot=short&amp;r=json",
      type: "GET",
      crossDomain: true,
      dataType: "JSON",
      success: function(val) {
        if (!val.Error) {
          movie = title.replace(/[^a-z0-9\s]/gi, '');
          $("#app").append(
            // appending info to divs
          );
        }
      }
    });
    if (isLast) countTheMovies();
  };
  
  function countTheMovies() {
    $("#app").append("There are " + $(".movie").length + " movies.");
  }
  </code></pre>
  
  <p>A plunker of my failings: <a href="https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview" rel="nofollow">https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview</a></p>