Skip to content

Instantly share code, notes, and snippets.

@teone
Last active January 31, 2016 02:53
Show Gist options
  • Select an option

  • Save teone/9f0d82f4f1bbcc338544 to your computer and use it in GitHub Desktop.

Select an option

Save teone/9f0d82f4f1bbcc338544 to your computer and use it in GitHub Desktop.
Async Loop With Generators and Promises
'use strict';
// async function (eg: rest call)
const makeRequest = function (endpoint) {
return new Promise(function (resolve, reject) {
resolve(endpoint);
});
}
// generator function
// iterates over an array and call several time the async function
const generator = function* (resources) {
for(let endpoint of resources){
let foo = yield makeRequest(endpoint);
console.log(foo);
}
};
// Instantiate the generator,
// call next passing the value when the promise has been resolved,
// untill the generator has completed, then return the last promise value,
const run = function(generator, resources) {
var it = generator(resources);
function go(res){
// if the generator has ended return the value
if(res.done){
return res.value;
}
//else wait for promise and call generators.next()
return res.value
.then((res) => {
go(it.next(res));
})
.catch((e) => {
it.throw(e);
});
}
go(it.next());
}
// execution
const resources = ['endpont1', 'endpoint2', 'endpoint3'];
run(generator, resources);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment