Node.js,Promises&递归 - 可能吗?

时间:2015-05-02 20:09:05

标签: javascript node.js recursion paypal promise

我想从paypal检索交易,直到找不到更多的交易。 我想在使用递归函数时这样做。 我无法弄清楚如何做到这一点。 有可能吗?

我可以进行递归,但不能聚合事务并将它们传递出函数。

为简单起见,我删除了非相关行。

this.retrieveAllTransactionsBetween = function(end_date, start_date) { 
    return getTransactions({
                STARTDATE: Moment(start_date).format().replace('+00:00', 'Z'),
                ENDDATE: Moment(end_date).format().replace('+00:00', 'Z')
            })
            .then(function(transactions){
                if (end) { // test for end of transactions
                    return [];
                }
                console.log('finish transactions in iteration where earliest was',earliest.toDate());
                return transactions.concat(retrieveAllTransactionsBetween(earliest.toDate(), start_date, customer_id));
            })
            .catch(function(e){
                console.error('getAllTransactionsBetween general error', e);
            })
    ;
};

this.getTransactions = function(dates) {
    var stringified_api_call_param = QueryString.stringify(api_call_params);

    return new Promise(function(resolve, reject) {
        var sequence = Sequence.create();
        sequence
            .then(function (next) {
                api_call_options.headers = {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Content-Length': Buffer.byteLength(stringified_api_call_param)
                    }
                ;

                var req = https.request(api_call_options, paypal_helpers.paypalCallbackWrapper(next));
                req.on('error', function(e) {
                    return reject(e.message);
                });
                req.write(stringified_api_call_param);
                req.end();
            })
            .then(function (next, res){
                return resolve(res);
            });
    });
};

1 个答案:

答案 0 :(得分:2)

这部分错了:

 return transactions.concat(retrieveAllTransactionsBetween(earliest.toDate(), start_date, customer_id));

您希望等待进行递归调用,.concat是一个数组函数。你应该等待它:

 return retrieveAllTransactionsBetween(earliest.toDate(), start_date, customer_id).
        then(function(more){ return transactions.concat(more); });
相关问题