纪念两个算法

1、如何使用promise,做到无限then

代码如下

function reducePromise(promiseArrGen) {
    promiseArrGen.reduce((pre, next) => {
        return pre.then((data) => {
            console.log(data);
            return next(data);
        })
    }, Promise.resolve(0))
}

function createPromise(i) {
    return () => {
        return new Promise((resolve, reject) => {
            setTimeout(()=>{
                resolve(i)
            }, 1000)
        })
    }
}

let PromiseArrGens = []

for(var i = 1; i < 10; i++) {
    PromiseArrGens.push(createPromise(i))
}

reducePromise(PromiseArrGens);

reducer 的本质是递归,有很沙雕的方法,实现promise无限then

let reducePromise = (PromiseArr) => {
    if(PromiseArr.length ===0 ) {
        return
    }
    return PromiseArr.splice(0, 1)[0]().then(data => {
        console.log(data);
        reducePromise(PromiseArr)
    });
}

function createPromise(i) {
    return () => {
        return new Promise((resolve, reject) => {
            setTimeout(()=>{
                resolve(i)
            }, 1000)
        })
    }
}

let PromiseArrGens = []

for(var i = 1; i < 10; i++) {
    PromiseArrGens.push(createPromise(i))
}

reducePromise(PromiseArrGens);

 

2、使用递归做加法

//递归做加法
add = (n) => {
    if([0].includes(n)) {
        return n;
    }
    
    return n + add(n-1);
}

console.log(add(10))

 

posted on 2020-04-02 20:41  杨龙飞  阅读(194)  评论(0编辑  收藏  举报

导航

Fork me on GitHub