如何使用promises返回从递归AJAX调用构建的集合?

时间:2015-12-25 20:48:17

标签: javascript ajax recursion promise

我正在从soundcloud API请求数据。它为每个请求提供200个磁道的json结果,以及一个名为“next_href”的字段,它基本上是接下来200个结果的API调用(或者保留很多)。这就是为什么我必须做一个递归函数。目前,我能够获得完整的集合,并在递归结束时解决承诺。但是,我不确定如何将集合返回到main函数。在我重新构造此函数以使用promise之前,我只是在递归的最终回调中调用addTracks,这很有用,但我想抽象函数,以便它可用于任何soundcloud API调用。

这是我到目前为止所做的:

function main(){
    // Use the user's soundcloud ID to request the their likes
    var url = "https://api-v2.soundcloud.com/users/" + userid + "/likes?offset=0&limit=200";

    var promise = getCollection(url);
    promise.then(function(collection){
    console.log("got here");
    //would like to have the collection to use here
    //addTracks(req, res, collection, 0);
    })  
}

function getCollection(url){
    var deferred = Q.defer();
    recurse(url, [], deferred);
    return deferred.promise;
}

function recurse(url, collection, promise){
    console.log(url);
    requestify.get(url).then(function(response){

        collection = collection.concat(response.getBody().collection);

        console.log(collection.length);

        if (response.getBody().next_href != null){
            var newurl = response.getBody().next_href;
            recurse(newurl, collection, promise);
        }
        else {
            promise.resolve();
        }

    })

}

1 个答案:

答案 0 :(得分:2)

您不需要使用延迟。 相反,只需返回下一步的承诺:

function main(){
    // Use the user's soundcloud ID to request the their likes
    var url = "https://api-v2.soundcloud.com/users/" + userid + "/likes?offset=0&limit=200";

    var promise = getCollection(url);
    promise.then(function(collection){
    console.log("got here");
        //would like to have the collection to use here
        addTracks(req, res, collection, 0);
    });  
}

function getCollection(url){
    return recurse(url, []);
}

function recurse(url, collection){
    console.log(url);
    return requestify.get(url).then(function(response){

        collection = collection.concat(response.getBody().collection);

        console.log(collection.length);

        if (response.getBody().next_href != null){
            var newurl = response.getBody().next_href;
            // Wait for the next call to complete and return its result.
            return recurse(newurl, collection);
        } else {
            // This is the final result of the promise
            return collection;
        }
    })

}