Introduction to Generators (ES2015) & Async Functions (ES2016)

Posted on Jan 9, 2016

class: center, middle

Generators & Async Functions

by Ivan Fraixedes

Twitter/Github: @ifraixedes

ivan.fraixed.es


class: middle

Agenda

1. Introduction to Generators Functions

2. Introduction to Async Functions

3. Using Generators as Async functions


Generators Functions

Generators has been standardized in EcmaScript 2015 Function generators can be created in two manners

  • with the function * declaration (syntax);
      function* myGenerator(...) {...}
    
  • using GeneratorFucntions constructor. The performance is worse because they are parsed a the execution time than with the reset of the code; they are a similar thing as eval()
    // GeneratorFunction is NOT a global object
    var GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor
    var g = new GeneratorFunction("a", "yield a * 2");
    

???

We can think in generators as functions witch can be exited at specified points of the execution and continue from the last exited point when they are called again keeping the context between them as a normal function does during its execution.

Generators return values before they finish using the statement yield; iterators execution finish when they reach the end of the “function” or execute “return” as an usual function does.

There is also the statement yield* to subrogate the execution to other generator; hence when that happens the caller generator give the flow to the callee generator and when it finishes the caller follows from that point.

Generators can be used to create iterables and get the same result in easy way than complex iterators; however this is out the context of this talk.


class: center, middle

Generators Function Demo


Async Functions

Async functions is a proposal for EcmaScript 2016, which is in draft.

Async functions are normal functions which can be suspended to await for promises.

The syntax looks as

async function myAsyncFunc(...) {
  // do whatever
  let result = await iReturnAPromise();
  // more things todo after the promise is resolved
}

class: center, middle

Async Functions Demo


class: center, middle

Generators as Async functions

We can use Function Generators as Async Functions, so we can think Async Functions as syntax sugar

Let’s see how

??? http://www.ecma-international.org/ecma-262/6.0/#sec-generator.prototype.next


class: center, middle

Credits

Mozilla Developers Network

Async functions proposal


Resources

Presentation: goo.gl/ZKSkTV

Source code (gist): goo.gl/4ZqC6z

– count: false

Feedback

I’d love to hear from you, say hi! on

Twitter: @ifraixedes

email: ivan@fraixed.es

Or any other way that you know that you can reach me!

count: false