I understand how to use generators to make async code look nice. I have a simple generator *all
, that takes a page
, will return a single value.
Then I have another generator *allDo
, that will use *all
for pages 1 to 30 and for each result, do some async task
.
Then I have another generator *allBatchDo
, that will batch 3 pages, and do some async task
.
function mockPromise(value) {
return Promise(function(resolve, reject) {
resolve(value);
});
}
function *all(page) {
var ls = yield mockPromise("page " + page);
// do all kinds of promises
return yield ls;
};
function *allDo(task) {
var page = 1;
while (true) {
var res = yield * all(page);
res = yield task(res);
if (page == 30) {
break;
}
page++;
}
}
function *allBatchDo(task) {
var page = 1;
var arr = [];
while (true) {
var res = yield * all(author, page);
arr.push(res);
if (arr.length >= 3) {
yield task(arr);
arr = [];
}
if (page == 30) {
break;
}
page++;
}
}
function logTask(res) {
return mockPromise(res).then(function(v) {
console.log(v);
});
}
Example use of these generators would be:
// return a single page promise
async(all(1)).then(function(value) { console.log(value); });
// do `logTask` for all pages 1 thru 30
async(allDo(logTask));
// do `logTask` for all pages with batches of 10
async(allBatchDo(logTask));
The question is, is this a legitimate use of es6 async features, or is there an abstract built-in solution for my use case?