简体   繁体   English

Node.js,承诺和递归-可能吗?

[英]Node.js, Promises & Recursion - Possible?

I want to retrieve transactions from paypal until there is no more transactions to retrieve. 我想从贝宝(Paypal)检索交易,直到没有其他交易可检索。 I would like to do it while using recursive function. 我想在使用递归函数时做到这一点。 I do not manage to figure out how to do it. 我不知道该怎么做。 Is it possible? 可能吗?

I can do the recursion but no to aggregate the transactions and pass them out of the function. 我可以进行递归,但不能汇总事务并将它们传递出函数。

I removed non relevant lines for simplicity. 为了简单起见,我删除了不相关的行。

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

This part is wrong: 这部分是错误的:

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

You want to wait for the recursive call, .concat is an array function. 您要等待递归调用, .concat是一个数组函数。 You should wait for it: 您应该等待:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM