promise基于reduce实现队列消息


function dosomething(num) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(num);
            if(num > 4) reject(num);
            else resolve(num);
        }, num * 1000);
    });
}

function queue(arr, thing) {
    return arr.reduce((promise, params) => 
                new Promise((resolve, reject) => {
                    promise.then(results => {
                        thing.call(null, params).then(r => {
                            resolve([...results, r]);
                        }).catch(e => {
                            reject(e);
                        });
                    })
                }),
                Promise.resolve([]));
}





queue([4, 1, 3, 2], dosomething).then(res => {
    console.log('succes', res);
}).catch(err => {
    console.log('error', err);
});

// 输出
// 4
// 1
// 3
// 2
// succes [4, 1, 3, 2]

 

posted @ 2020-11-13 15:52  oneall  阅读(520)  评论(0编辑  收藏  举报