Javascript 如何使用承诺返回从递归AJAX调用生成的集合?

Javascript 如何使用承诺返回从递归AJAX调用生成的集合?,javascript,ajax,recursion,promise,Javascript,Ajax,Recursion,Promise,我正在从soundcloud API请求数据。它提供了json结果,每个请求有200个跟踪,以及一个名为“next_href”的字段,该字段基本上是对下200个结果(或剩余多少)的API调用。这就是为什么我必须做一个递归函数。目前,我能够获得完整的集合,并在递归结束时解析承诺。但是,我不确定如何将集合返回到主函数。在我重新构造这个函数以使用promise之前,我只是在递归的最终回调中调用addTracks,这很有效,但我想抽象这个函数,以便它可以用于任何soundcloud API调用 以下是我

我正在从soundcloud API请求数据。它提供了json结果,每个请求有200个跟踪,以及一个名为“next_href”的字段,该字段基本上是对下200个结果(或剩余多少)的API调用。这就是为什么我必须做一个递归函数。目前,我能够获得完整的集合,并在递归结束时解析承诺。但是,我不确定如何将集合返回到主函数。在我重新构造这个函数以使用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();
        }

    })

}

你不需要使用延期。 相反,只需回报下一步的承诺:

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;
        }
    })

}