简体   繁体   English

对异步调用的承诺进行递归

[英]Recursion with promises on async calls

I am using an external api that I use as my datasource. 我正在使用用作数据源的外部api。 That api gives its data back based on a pagination like type. 该api根据类似分页的类型提供其数据。

So I can get data for page 1, 2, 3 etc. But the problem that I have is that I need all data at once, the api doesn't support this so I write it myself. 因此,我可以获取第1、2、3等页的数据。但是我遇到的问题是,我需要一次获取所有数据,api不支持此数据,所以我自己编写。

I have made the actual call code: 我已经做了实际的呼叫代码:

function getTransactionPart(start){
        return new Promise(function(resolve, reject) {

            const options = {
                url: 'myurl?limit=40&start='+start,
                json: true
            };

            let result = {total_transactions : 0, transactions : []};

            request(options, function (error, response, body) {

                if (error) {
                    return reject(result);
                }

                body.data.forEach(function (transaction) {
                        result.transactions.push({
                            timestamp: transaction.timestamp,
                            amount: transaction.amount,
                            confirmed: transaction.confirmed
                        });
                });

                result.total_transactions = body.total

                return resolve(result);
            })
        })
    }

The above code returns me the expected results with the limit that I gave. 上面的代码以给定的限制向我返回了预期的结果。 Also I get a number back (result.total_transactions) when this is more than 40 I need to make another call with 40 as start etc etc. 当这个大于40时,我也会得到一个数字(result.total_transactions),我需要用40作为开始等进行另一个呼叫,等等。

The code where I need to combine it: 我需要将其组合的代码:

 function getTransactions(start) {
        return new Promise(function(resolve, reject) {

            getTransactionPart(start).then(result => {
                if(result.total_transactions > 40) {
                    //next call
                } else {
                    // return all?
                }
                console.log(result)
            }).catch(error => {
                console.error(error);
                return r.json({

                })
            });

        })
    }

So I do the first call with getTransactionPart(0) after that the method itself needs to combine the result form all the sub calls and return the whole result as expected. 因此,我首先使用getTransactionPart(0)进行了调用,之后该方法本身需要将所有子调用的结果组合在一起,并按预期返回整个结果。 How can I do this with recursion and promises? 我该如何使用递归和承诺?

This is easier if you use an async function and await the request: 如果您使用async函数并await请求,这会更容易:

  async function getTransactions(start) {
    const result = [];
    for(let pos = start; ; pos += 40) {
      const { total_transactions, transactions } = await getTransactionPart(pos);
      result.push(...transactions);

      if(total_transactions < 40) break;
    }
    return result;
 }

For sure you could also do this recursively, but do you really need that? 当然,您也可以递归执行此操作,但是您真的需要吗?

async function getTransactions(start) {
  const { total_transactions, transactions } = await getTransactionPart(pos);
  if(total_transactions < 40) 
     return transactions;

  return transactions.concat(await getTransactions(start + 40));
}

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

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