Soundcloud Javascript API SC.get()不允许我更改函数之外的变量

时间:2013-01-30 23:29:05

标签: javascript soundcloud

我似乎在Soundcloud Javascript API中遇到了SC.get函数的问题。我尝试将一个新项目推送到newSounds数组;但是,在_.each循环退出后,newSounds对象仍然是一个长度为0的数组。此外,在loadSounds执行后声音对象未定义。一些帮助将不胜感激,如果我需要发布更多帮助解决问题,请告诉我。

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 个答案:

答案 0 :(得分:2)

在这种情况下,棘手的问题是SC.get很可能是异步的,所以当你返回newSounds时,它几乎肯定是空的/不完整的。最重要的是,有多个SC.get要求管理。

在jQuery中使用deferred object,您可以像这样解决问题(受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;
}