Flying memes

Falling Stars: find one-hit wonders on Spotify

During this summer I got bored from my Spotify playlist and started hunting new songs, the task revealed harder than I thought and I end up coding a small website to achieve my goal.
Falling Stars helps you find one-hit-wonders and create a Spotify playlist out of those songs.

The most interesting part, apart from discovering the nice Spotify API was having to deal with an asynchronous loop; I had basically to loop over the Related Artists of a song and search if one of them is a one-hit-wonder. If not start again with the Related Artists of the first of the previous ones.

To implement the loop I decided to use Promises. Promises are a new way to deal with asynchronous operation without using callbacks. Basically a Promise is an object with a state that changes when the associated asynchronous operation succeed or fails. A Promise can store functions that needs to be executed when the asynchronous operation completes and, best of all, promises can be chained.

Here’s how I ended up with the loop:

  run: function(){
    var self = this;
    if( self.queue.length > 0 && self.playlist.length < self.limit ){
      self.parsed.unshift(self.queue.shift());
      self.parse(self.parsed[0])
        .then(self.populate.bind(self))
        .then(self.run.bind(self));
    }else{
      var playlist_name = 'Falling Stars - ' + new Date();
      self.api('POST','/users/' + self.userId + '/playlists', {
        name: playlist_name,
        public: false
      }).then(function(result){
        self.api('POST','/users/' + self.userId + '/playlists/' + result.id + '/tracks', 
          self.playlist.map(function(track){
            return track.uri;
          })
        ).then(function(){
          self.message('playlist', playlist_name);
        });
      });
    }
  }

The rest of the code is available on github and the project is online here: http://fallingstars-sandropaganotti.rhcloud.com/

Tags: ,