zoukankan      html  css  js  c++  java
  • 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]
  • 相关阅读:
    jquery弹出窗口
    js定时器
    jquery树形菜单
    用convert转换参数对比
    jquery常用例子!
    JS总结
    上传简历实现只浏览不下载的效果
    区块链入门(1):搭建(Ubuntu系统)Truffle v3.2.1 开发和测试环境
    URL Routing组件是如何与ASP.NET MVC框架组合起来的
    接单网站收集
  • 原文地址:https://www.cnblogs.com/oneall/p/13969759.html
Copyright © 2011-2022 走看看