0

Possible Duplicate:
Waiting on multiple asynchronous calls to complete before continuing

Update:

Here is the HTML form that lets the user select one or more timelines:

<form>
  <ul>
    <li>
      <input type="checkbox" id="s-fry" data="stephenfry" />
      <label for="s-fry">Stephen Fry</label>
    </li>
    <li>
      <input type="checkbox" id="r-dawkins" data="richarddawkins" />
      <label for="r-dawkins">Richard Dawkins</label>
    </li>
    <li>
      <input type="checkbox" id="s-macfarlane" data="sethmacfarlane" />
      <label for="s-macfarlane">Seth MacFarlane</label>
    </li>
    <li>
      <input type="checkbox" id="r-gervais" data="rickygervais" />
      <label for="r-gervais">Ricky Gervais</label>
    </li>
  </ul>
  <input type="submit" value="Go" />
</form>
<div id="tweets"></div>

And here's the JavaScript

$('input[type=submit]').on('click', function(e){

// prevent default behavior of the submit button
e.preventDefault();

// empty the div with ID of tweets
$('#tweets').empty();

// create an empty ul
var tweetList = $('<ul id="tweets-list">');

// create an empty array for the tweets
var returnedTweets = [];

// perform a function on all of the checked boxes
$(':checkbox:checked').each( function(){

var twitterID = $(this).attr('data');

// use the "data" attribute to build the query string for getJSON
$.getJSON( 'http://api.twitter.com/1/statuses/user_timeline/'+twitterID+'.json?callback=?', null, function(data){
    $.each(data, function(i, tweet){ 
      returnedTweets.push(tweet); 
    });
    returnedTweets.sort(function(a,b){ return b.id - a.id; });
    $.each(returnedTweets, function(i, tweet){
      var item  = $('<li>');
      var name  = $('<h2>').text(tweet.user.name);
      var date  = $('<small>').text(prettyDate(tweet.created_at));
      var img   = $('<img>').attr('src', tweet.user.profile_image_url);
      var msg   = $('<p>').text(tweet.text);
      item.append(img,name,date,msg);
      tweetList.append(item);
    }); // end of parse
}); // end of getJSON
}); // checkbox.each

$('#tweets').append(tweetList);

function prettyDate(time){
var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);

if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
return;

return day_diff == 0 && (
      diff < 60 && "just now" ||
      diff < 120 && "1 minute ago" ||
      diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
      diff < 7200 && "1 hour ago" ||
      diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
  day_diff == 1 && "Yesterday" ||
  day_diff < 7 && day_diff + " days ago" ||
  day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
} // end of prettyDate

}); // end of "click" function

It is sorting the array before output, but it's not sorting chronologically, as intended. Here is an updated fiddle: http://jsfiddle.net/brianeoneill/FsYKg/

Community
  • 1
  • 1
Brian O'Neill
  • 4,705
  • 5
  • 22
  • 26

1 Answers1

0

If you want to wait until all callbacks have completed before logging, then try creating an array of Deferred... then when they all have completed, you will have a fully populated list.

http://api.jquery.com/jQuery.when/

Something like this may work:

var returnedTweets = [];
var deferreds = [];

$(':checkbox:checked').each( function(){

    deferreds.push($.getJSON( 'http://api.twitter.com/1/statuses/user_timeline/'+$(this).attr('data')+'.json?callback=?', null, function(data){
        $.each(data, function(i, tweet){ 
           returnedTweets.push(tweet); 
        });
    }));

});

$.when(deferreds).then(
    function () {
       console.log(returnedTweets.length);
    });
Glen Hughes
  • 4,712
  • 2
  • 20
  • 25