1

I'm making a web app called "Your Life in Music" where the user plugs in his/her birthdate and the app displays the top billboard hit from each birthday since they were born. The app talks to the Last.fm api to retrieve the album art for each song. Currently it takes a while for the app to compile all the album art and someone suggested speeding things up by combining all the API calls into a single request. I'm a bit of a newbie though, and I'm not sure this can be done. So my question: How does one combine multiple calls into a single request?

Here's the app: http://www.dailyspiro.com

And the critical code:

function compileDisplay(birthDays) {
// create an HTML list that for each birthday displays top song, artist, and album art
htmlObj = {}
for (i = 0; i < birthDays.length; i++) {
    var age = birthDays[i][0]; // age isn't equal to i if user was born before 1958
    var date = birthDays[i][1];
    var track = billboard[date]['song'];
    var artist = billboard[date]['artist'];
    getAlbumArt(age, track, artist, birthDays);
  }
}

function getAlbumArt(age, track, artist, birthDays) {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=(myApiKey)&artist=" + artist + "&track=" + track + "&format=json&callback=?", function (data) {
    try {
        var image = data.track.album.image[2]['#text'];
        if (image == 'http://cdn.last.fm/flatness/catalogue/noimage/2/default_album_medium.png') {
            throw 'generic image';
        }
    } catch (err) {
        var image = 'images/' + track + '.jpg';
    }
    compileHtml(age, track, artist, image, birthDays)
  })
}
Ben Davidow
  • 1,175
  • 5
  • 23
  • 51
  • possible duplicate of [Parallel asynchronous Ajax requests using jQuery](http://stackoverflow.com/questions/1060539/parallel-asynchronous-ajax-requests-using-jquery) – Timur Sadykov Aug 13 '13 at 23:39

1 Answers1

3

Whether you can batch API calls together is up to the API itself. I had a quick look at the API and did not found anything allowing to batch multiple operations. I also checked for a method that would allow retrieving multiple track infos at once without any success. It seems that you are out of luck.

However, you could implement some sort of caching to avoid performing these requests all the time. For instance, you could have your own server-side service which acts as a middle-tier between the lastfm API and the client application. That server-side API would then implement caching and any other optimization logic.

plalx
  • 42,889
  • 6
  • 74
  • 90