How can I do pagination with Bluebird Promises?

前端 未结 3 1098
北荒
北荒 2021-01-02 17:24

I have something like

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

    resolve trade         


        
3条回答
  •  粉色の甜心
    2021-01-02 18:05

    Here's my own solution to paging through promises: method page, as part of the spex library.

    It also lets you throttle the processing and provide load balancing as needed.

    Example

    var promise = require('bluebird');
    var spex = require('spex')(promise);
    
    function source(index, data, delay) {
        // create and return an array/page of mixed values
        // dynamically, based on the index of the sequence;
        switch (index) {
            case 0:
                return [0, 1, promise.resolve(2)];
            case 1:
                return [3, 4, promise.resolve(5)];
            case 2:
                return [6, 7, promise.resolve(8)];
        }
        // returning nothing/undefined indicates the end of the sequence;
        // throwing an error will result in a reject;
    }
    
    function dest(idx, data, delay) {
        // data - resolved array data;
        console.log("LOG:", idx, data, delay);
    }
    
    spex.page(source, dest)
        .then(function (data) {
            console.log("DATA:", data); // print result;
        });
    

    Output

    LOG: 0 [ 0, 1, 2 ] undefined
    LOG: 1 [ 3, 4, 5 ] 3
    LOG: 2 [ 6, 7, 8 ] 0
    DATA: { pages: 3, total: 9, duration: 7 }
    

提交回复
热议问题