Skip to content

Instantly share code, notes, and snippets.

@sramam
Created February 21, 2018 02:52
Show Gist options
  • Save sramam/f3894fe4d4a56e83aaaf16c4a93da7f7 to your computer and use it in GitHub Desktop.
Save sramam/f3894fe4d4a56e83aaaf16c4a93da7f7 to your computer and use it in GitHub Desktop.
understanding async generators
import * as delay from 'delay';
(<any>Symbol).asyncIterator = Symbol.asyncIterator || Symbol.for("Symbol.asyncIterator");
async function* g() {
yield 1;
await delay(100);
yield* [2, 3];
yield* (async function *() {
await delay(100);
yield 4;
})();
}
async function f() {
for await (const x of g()) {
console.log(x);
console.log(`---`);
}
}
f().catch(err => console.log(`error: ${err}`));
async function* ii() {
let idx = 0;
yield idx++;
await delay(100);
yield idx++;
yield idx++;
yield idx++;
return 'return';
}
async function h() {
const gg = ii();
console.log(await gg.next());
console.log(await gg.next());
console.log(await gg.next());
console.log(await gg.next());
console.log(await gg.next());
console.log(await gg.next());
}
h().catch(err => console.log(`err:${err}`));
async function* kk() {
let idx = 0;
yield;
idx++;
await delay(100);
yield;
idx++;
yield
idx++;
yield
idx++;
return idx;
}
async function k() {
const gg = kk();
let result;
while((result = await gg.next()).done === false) {
console.log(`k: ${JSON.stringify(result)}`);
delay(1000);
}
console.log(result);
}
k().catch(err => console.log(`err:${err}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment