Javascript Async Generator
Is it possible to write an asynchronous generator like the following: function gen() { return async function * () { yield await ... yield await ... yield await ...
Solution 1:
Until the async iteration proposal is complete, you could take a page from the Redux-saga book (like Cory Danielson mentioned) and have an adapter function that does all the async/await stuff.
const later = async (delay, value) => {
returnnewPromise(resolve => {
setTimeout(() =>resolve(value), delay);
});
};
function* rangePromise() {
for (let i = 2; i < 10; i++) {
let nextValue = yieldlater(100, i);
yield nextValue;
}
}
const forEachAsyncAdapter = async (iterator, ...callbacks) => {
try {
let next = iterator.next();
while (!next.done) {
while (!next.done && next.value && next.value.then) {
next = iterator.next(await next.value);
}
if (!next.done) {
await callbacks.reduce(
async (nextValue, callback) => {
nextValue = awaitcallback(await nextValue);
return nextValue;
},
Promise.resolve(next.value)
);
next = iterator.next();
}
}
} finally {
if (typeof iterator.return === 'function') {
iterator.return();
}
}
};
forEachAsyncAdapter(
rangePromise(),
async i => { console.log(i); returnArray(i).join('a'); },
async s => { console.log(s); return s.toUpperCase(); },
async s => { console.log(s); }
);
Post a Comment for "Javascript Async Generator"