ES6 Generators
(and maybe a little arguments + destructuring, too)
Generators - Function or Object?
- Generator functions return the generator object
- Generator object conforms to iterable and iterator protocols
Generator Function
- Special type of function that can pause & resume execution
- Automatically generates an iterator
- Utilizes "yield" keyword to indicate the value returned for each call to next()
Wait - what's an iterator?
- iterators return an object with a next() method on it
- if wanted, you could manually iterate like above
why iterate manually...for-of handles this for us!
You can create custom iterators
OK - Back to Generator Functions
- Special type of function that can pause & resume execution
- Automatically generates an iterator
- Utilizes "yield" keyword to indicate the value returned for each call to next()
- yield pauses execution inside generator function
- for-of iteration automatically calls "next()" on the generator (until no more values are yielded)
What the Generator Function Returns
Manually Calling Next
Generators are Lazy
Generators ♡ Destructuring
Generators ♡ ...Spread
Generators ♡ Other Generators
Generators ♡ Custom Iterables
A Sidebar on ES6 Spread
- new operator full of chocolatey goodness :-)
- spread an expression over multiple arguments
- can work with any iterable!
Spreading Arguments
Iterables all Around!
Since We Brought Up Arguments...
This is confusing:
configureServer( "196.168.0.1", "8787", true, true );
But, why?
This is better:
configureServer({
server: "196.168.0.1",
port: "8787",
enableCache: true,
logFailures: true
});
But this is verbose
function configureServer( options ) {
options.port = options.port || "8888";
// both setting defaults and having to
// use dot notation off of options
}
ES6 Destructuring FTW
What About Default Params?
What About Required Params?
Aaaand we're done
ES6 Generators
By Jim Cowart
ES6 Generators
Informal LeanKit web team training slides
- 927