Created
February 21, 2018 02:52
-
-
Save sramam/f3894fe4d4a56e83aaaf16c4a93da7f7 to your computer and use it in GitHub Desktop.
understanding async generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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