for-await-of simple example (typescript) -
in typescript 2.3 new feature introduced for-await-of can post simple example of how use same promise , main use case of same, looking example in there change log
async function f() { await (const x of g()) { console.log(x); } } but not understand use case
here's sample uses for-await-of print "1", wait second , print "2":
// polyfill symbol.asynciterator (symbol any).asynciterator = symbol.asynciterator || symbol("symbol.asynciterator"); async function sleep(ms: number): promise<void> { return new promise<void>((resolve, reject) => { settimeout(resolve, ms); }); } async function* asyncgenerator() { yield 1; await sleep(1000); yield 2; } (async() => { await (const num of asyncgenerator()) { console.log(num); } })().catch(e => console.error(e)); the typescript 2.3 release notes have helpful caveats
- you need include
esnextincompileroptions.libsetting oftsconfig.json(or in--libcommand line flag). - you need set
compileroptions.downleveliteratorsintsconfig.json(or--downleveliteratorson command line). - you may need
symbol.asynciteratorpolyfill (included in snippet above).
Comments
Post a Comment