Pergunta

I'm trying to learn more about jquery deferred/promises. I sort of understand when you want to do 1 ajax call, but what about doing multiple (x number) ajax calls together? Here is a jsfiddle of what I'm trying to do: http://jsfiddle.net/vRJ7v/

For example (using the lastFM api):

var last_fm_url = 'http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user='; 
var apiKey = //my lastfm api key;
var user_list = ['user1','user2'.....'userX'];

var getTracks = function( user ){
    var dfd, last_fm_url;

    dfd = $.Deferred();

    last_fm_url = last_fm_url + user + '&limit=10&period=3month&api_key='+ apiKey +'&format=json';

    $.getJSON( last_fm_url ).done(function( results ) {
        dfd.resolve();
    }).fail(function( error ) {
        dfd.reject();
    });

    return dfd.promise();

};

var fetchMultipleTracks = function(){
     var dfd, user_list_count, promises = [];

     var dfd = $.Deferred();

     user_list_count = user_list.length;

     for(var i = 0; i < user_list_count; i++ ){
         promises.push( getTracks(user_list[ i ]) );
     }

     $.when( promises ).done(function(results){
         dfd.resolve();
     });

     return dfd.promise();
};

var test = fetchMultipleTracks();
test.done(function( results ){
  console.log( results );  
}, function( error ){
    // error
});

But I can't seem to return the actual results, it just returns http://d.pr/i/N5Yi

Foi útil?

Solução

$.when accepts one promise per argument, not an array of promises. If you wish to use an array, you must use .apply so that you'll apply the array of promises to the .when method properly.

$.when.apply($,myArrayOfPromises).done(...

Additionally, $.when returns a promise, so you do not need to generate another one.

var fetchMultipleTracks = function(){
     var user_list_count, promises = [];

     user_list_count = user_list.length;

     for(var i = 0; i < user_list_count; i++ ){
         promises.push( getTracks(user_list[ i ]) );
     }

     return $.when.apply($, promises );
};

To handle the results, iterate over the arguments array.

get_tracks.done(function(){
   $.each(arguments,function(i,result) {
      console.log(result)
      outputTracksToDom(result.toptracks.track);
   });
}).fail(function(error ){
    // handle error
});

http://jsfiddle.net/vRJ7v/1/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top