尝试使用node.js和javascript中的promises递归查询reddit

时间:2014-12-09 07:07:31

标签: node.js promise

我正试图弄清楚如何重新查询此端点。我一次只能得到100个结果,总共最多1000个。所以我想将所有结果收集到一个数组中,然后在最后返回1000个集合。

function getComments(before){
    var where = {
        sort: 'new',
        limit: 100
    };

    if ( before ) {
        where.before = before;
    }

    return reddit('/user/'+cmd.user+'/comments').listing(where)
        .then(function(data){
            logger.log('info', data);
        }).catch(function(err){
            logger.error(err);
        });
}

以下是我尝试设置此递归调用的方法:

function getAllComments(){
    var def = q.defer();

    getComments()
        .then(function(data){
            var before = data[data.length].id;
            //call getComments(before) here

        });


    return def.promise;
}

1 个答案:

答案 0 :(得分:-1)

then回调中返回一个承诺,然后在then来电的结果上递归添加另外8个then来电。

http://jsfiddle.net/BWNba/50/

function getComments(before) {
    if(typeof before === 'undefined') {
        before = 0;
    }
    var deferred = Q.defer();
    deferred.resolve([before+1,before+2,before+3]);
    return deferred.promise;
}

function getCommentsAndMergeWithPrevious( previousData, before) {
    return getComments(before).then(function(newData) {
         return previousData.concat(newData);
    });
}

function getAllComments(){
    var promise = getComments();

    for(var i = 0; i < 9; i++) {
       promise = promise.then(function(data){
            var before = data[data.length-1];
            return getCommentsAndMergeWithPrevious(data, before);
        });
    }

    return promise;   
}

getAllComments().then(function(data) {
    console.log(data);
}).catch(function(data) {
    console.log(data);
});

记录下列结果

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]