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 esnext in compileroptions.lib setting of tsconfig.json (or in --lib command line flag).
  • you need set compileroptions.downleveliterators in tsconfig.json (or --downleveliterators on command line).
  • you may need symbol.asynciterator polyfill (included in snippet above).

Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -