本文介绍了如何使用 Bluebird Promises 进行分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的东西

new Promise (resolve, reject) ->
  trader.getTrades limit, skip, (err, trades) ->
    return reject err if err

    resolve trades
.each (trade) ->
  doStuff trade

limit 被设置为任意数字,比如 10skip0 开始.我想继续增加 skip 直到没有更多的 trades.

limit is set to some arbitrary number, say 10 and skip starts at 0. I want to keep increasing skip until there are no more trades.

doStuff 是我用来处理每笔交易的函数.

The doStuff is a function I'm using to process each trade.

这是第一次有效,但我想以分页方式获得更多交易.具体来说,我想以更高的 skip 运行 trader.getTrades 直到 trades.length 为 0

This works the first time, but I want to get more trades in a paginated fashion. Specifically, I want to run trader.getTrades with a higher skip until trades.length is 0

推荐答案

你应该能够使用 promisify()/promisifyAll()trader.getTrades() 转换为返回承诺的异步版本.然后,这样的事情应该可以正常工作:

You should be able to use promisify()/promisifyAll() to convert trader.getTrades() to an async version that returns a promise. Then, something like this should work well:

function getAllTrades(limit, offset, query) {

    var allTrades = [];

    function getTrades(limit, offset, query){
        return trader.getTradesAsync(limit, offset, query)
            .each(function(trade) {
                allTrades.push(trade)
                // or, doStuff(trade), etc.
            })
            .then(function(trades) {
                if (trades.length === limit) {
                    offset += limit;
                    return getTrades(limit, offset, query);
                } else {
                    return allTrades;
                }
            })
            .catch(function(e) {
                console.log(e.stack);
            })
    }

    return getTrades(limit, offset, query)
}

如果您事先知道交易的总数,您可以使用 .map{concurrency: N} 的不同策略一次获得 N 页的交易.

If you knew the total # of trades in advance you could use a different strategy with .map and {concurrency: N} to get N pages of trades at once.

这篇关于如何使用 Bluebird Promises 进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-08 20:04