无法将项目推送到阵列

时间:2013-02-01 21:26:53

标签: javascript

  

可能重复:
  Waiting on multiple asynchronous calls to complete before continuing

更新:

以下是允许用户选择一个或多个时间轴的HTML表单:

<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>

这是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

它在输出之前对数组进行排序,但它没有按照预期按时间顺序排序。这是一个更新的小提琴:http://jsfiddle.net/brianeoneill/FsYKg/

1 个答案:

答案 0 :(得分:0)

如果你想等到所有回调都在记录之前完成,那么尝试创建一个Deferred数组...然后当它们全部完成时,你将有一个完全填充的列表。

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

这样的事情可能有用:

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);
    });