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

How to use promises to return a collection built from a recursive AJAX call?

本文关键字:调用 构建 集合 AJAX 递归 何使用 promise 返回      更新时间:2023-09-26

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