簡體   English   中英

Node.js,承諾和遞歸-可能嗎?

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

我想從貝寶(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);
            });
    });
};

這部分是錯誤的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM