Search code examples
javascriptapispotifypromisespotify-app

Chaining load calls in Spotify apps api


Using API v1.

Not sure how frequently I'll have to do stuff like this, but I suspect a fair bit.

I want to check if the user is the owner of a playlist dropped. Is it possible to do this without the nested load chaining below? I see that Promises can be joined, but I don't think I can load currentUser without having already loaded owner. Any way to simplify this?

    var drop = models.Playlist.fromURI(...);
    var success_message = document.createElement('p');
    success_message.innerHTML = 'Playlist successfully dropped: ' + drop.uri;
    this.appendChild(success_message);
    drop.load('owner').done(function (playlist) {
        playlist.owner.load('currentUser').done(function (owner) {
            if (owner.currentUser) {
                var allowed_message = document.createElement('p');
                allowed_message.innerHTML = 'You are the owner of this playlist, let\'s get to work!';
                drop_box.appendChild(allowed_message);
            }
            else {
                var disallowed_message = document.createElement('p');
                disallowed_message.innerHTML = 'You are not the owner of this playlist, choose a different one please!';
                drop_box.appendChild(disallowed_message);
            }
        });
    });

Solution

  • You are right, and yours is the best way of checking it. You need to make 2 asynchronous calls and chain them like that.

    An alternative would be to fetch first the identifier for the current user through models.session.user.load('username').done(function(u) { ... });, which returns the username, and then compared it with the uri of the owner of the playlist (prefixing the username with spotify:user:. But, as you can see, this alternative wouldn't save you from making 2 nested calls.