title: How to keep index straight when ajax request are async and not finishing in order
body: <p>I am interacting with the Vimeo oembed api getting videos.  My context is that I have multiple events each with a set of videos.  I am keeping page load times down by simply getting the first set of videos rather than loading all of them.</p>
  
  <p>This function takes 4 parameters and then gets the video, returning the result to the calling function for loading.  The videoUrl is <a href="http://www.vimeo.com/VIDEOID" rel="nofollow">http://www.vimeo.com/VIDEOID</a>, the index is based on a .each in the calling function which is iterating through available ID's, the count is a total number of videos that will be called and the callback handles the data getting back to the calling function.  Once the function is all done it calls showFirstVideo which shows a video for the first thumbnail I am generating.</p>
  
  <p>the issue I am having is that because the ajax calls are async, the indexEq var jumps around.  instead of: 0, 1, 2, 3, 4 ... it will be 1,6,3,0...</p>
  
  <p>I need the indexEq to increment in order so that at the end I can run the showFirstVideo function at the appropriate time.</p>
  
  <pre><code>function loadVideo(videoUrl, index, vidsCount, callback) {
      var indexEq = index;
      $.when(
          $.ajax({
              type : "GET",
              url : "http://www.vimeo.com/api/oembed.json",
              data : {"url" : videoUrl },
              dataType : "jsonp",
              success : function(result) {
                  index++;
                  callback(result);
              },
              error : function(error) {
                  var s = "";
                  $.each(error, function(name, value){
                      s += name + ": " + value + "\n";
                  });
              }
          })
      ).done(function(){
          console.log(indexEq);
          if(indexEq === vidsCount){
              $('.video-thumbs').velocity("fadeIn");
              $('.past-concert-loader').velocity("fadeOut");
              showFirstVideo();
  
              // RESET INDEX, FOR WHEN WE HAVE TO CALL THIS FUNCTION AGAIN.
              console.log("Trigger indexEq back to 1");
              indexEq = 1;
          }
      });
  }
  </code></pre>
  
  <p>The $.each that calls  this function:</p>
  
  <pre><code>$.each(vids, function(i, val){
          var videoUrl = 'http://www.vimeo.com/'+val+'';
          loadVideo(videoUrl, i, vidsLength, function(result){
              $('.video-thumbs').append('&lt;div class="col-xs-6 col-sm-3 video-thumb video-'+i+'" data-video-id="'+ result.video_id +'"&gt;&lt;img src="'+ result.thumbnail_url +'" alt="'+ result.title +'" class="img-responsive"&gt;&lt;/div&gt;');
          });
      });
  </code></pre>