Created
July 14, 2016 11:34
-
-
Save georgeOsdDev/b18cedbc15a644fa4bd39f498c1f7c90 to your computer and use it in GitHub Desktop.
recursive promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const recursivify = (api, params, accumurator, condition) => { | |
const exec = (acc) => { | |
return new Promise((resolve, reject) => { | |
api(params, resolve, reject); | |
}) | |
.then((v) => { | |
return Promise.resolve(accumurator(acc, v)); | |
}, | |
() => { | |
return Promise.resolve(acc); | |
}); | |
} | |
const recursiveHandler = (acc) => { | |
if (condition(acc)){ | |
return Promise.resolve(acc); | |
} else { | |
return exec(acc).then(recursiveHandler); | |
} | |
} | |
return exec().then(recursiveHandler) | |
} | |
var i = 0; | |
const myApi = (params, resolve, reject) => { | |
setTimeout(() => { | |
resolve(i++); | |
},100); | |
} | |
const myAccumurator = (acc, val) => { | |
if (!acc) { | |
return [val]; | |
} else { | |
return acc.concat(val); | |
} | |
} | |
recursivify(myApi, {}, myAccumurator, (acc) => acc.length > 10).then(function(v){console.log(v)}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment