Soundcloud Javascript API SC.get() will not allow me to change a variable outside of the function

做~自己de王妃 提交于 2019-12-08 05:57:32

问题


I seem to be having a issue with the SC.get function in the Soundcloud Javascript API. I try to push a new item to the newSounds array; however, after the _.each loop exits the newSounds object is still an array with length = 0. In addition the sounds object is undefined after loadSounds executes. Some help would be greatly appreciated, and if I need to post more to help solve the problem let me know.

loadSounds = function() {
    var newSounds = [];
    _.each(trackURLs, function(trackURL) {
      console.log(trackURL);
      SC.get(trackURL, function(track) {
        console.log(track.artwork_url);
        newSounds.push(track);
      });
    });
    return newSounds;
};

var sounds = loadSounds();

回答1:


The tricky thing in this case is that SC.get is most likely asynchronous, so when you go to return newSounds it will almost certainly be empty/incomplete. On top of that, there are multiple calls to SC.get to manage.

Using the deferred object in jQuery, you could solve your problem like this (inspired by http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects):

function loadSounds() {
    var newSounds = [];

    var deferredObjects = $.map(trackURLs, function (item, index) {
        var deferred = $.Deferred();

        SC.get(trackURL, function(track) {                 
            newSounds.push(track);
            deferred.resolve(track);
        });

        return deferred.promise();
    });

    $.when.apply(this, deferredObjects).then(function () {
        console.log('All done');
        console.log(newSounds);
    });

    return newSounds;
}


来源:https://stackoverflow.com/questions/14615831/soundcloud-javascript-api-sc-get-will-not-allow-me-to-change-a-variable-outsid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!