How can you map the results of async calls in a generator, concurrently?
var generator = (function *() {
var lotsOfThings = yield asyncTask.call(generator);
var mappedResults = yield lotsOfThings.map(thing => {
// fails with a syntax error unless you do a `for…of` loop, but also doesn’t run concurrently regardless
return (yield asyncTask.call(generator, thing));
});
// then do something with mappedResults
})();
generator.next();
function asyncTask(…query) {
somethingAsync(…query, (err, res) => this.next(res));
}
Also, even in a regular for...of
loop, you can’t run each asyncTask
concurrently. yield
will cause a pause between each task, essentially making a synchronous AJAX request. Ideally you’d want it to work like it does with promises, like this paradigm:
// these tasks will run concurrently (unlike the above example)
let promises = someThings.map(thing => {
return new Promise((resolve, reject) => {
somethingAsync((err, res) => {
resolve(res);
});
});
});
Promise.all(promises).then(/* do stuff */);
The promise approach can get hairy 'cause of all the nesting, but the benefit is that the async tasks can run concurrently… whereas the generators look nice, but looping through tasks is not concurrent. Any ideas?