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?
The syntax is simple: prepend function* with async . That makes the generator asynchronous. And then use for await (...) to iterate over it, like this: async function* generateSequence(start, end) { for (let i = start; i <= end; i++) { // Wow, can use await!
Among those features are generator functions and async/await. Generator functions give you the ability to pause and continue the execution of a program. In contrast, async/await gives you the ability to write asynchronous code without falling into "callback hell", which you risk when writing standard promises.
Async/await makes it easier to implement a particular use case of Generators. The return value of the generator is always {value: X, done: Boolean} whereas for async functions, it will always be a promise that will either resolve to the value X or throw an error.
If you want use generators to make async then you code is valid. ES6 contains only promises to async operations. ES7 will have async/await. You can also use a good library: https://github.com/kriskowal/q or use only native promises Promise.All without generators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With