Skip to content

Instantly share code, notes, and snippets.

@georgeOsdDev
Created July 14, 2016 11:34
Show Gist options
  • Save georgeOsdDev/b18cedbc15a644fa4bd39f498c1f7c90 to your computer and use it in GitHub Desktop.
Save georgeOsdDev/b18cedbc15a644fa4bd39f498c1f7c90 to your computer and use it in GitHub Desktop.
recursive promise
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