纪念两个算法
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))
学而不思则罔,思而不结则殆,结而不看,一事无成