Tutorial by Examples

A generator function is created with a function* declaration. When it is called, its body is not immediately executed. Instead, it returns a generator object, which can be used to "step through" the function's execution. A yield expression inside the function body defines a point at which...
A generator is iterable. It can be looped over with a for...of statement, and used in other constructs which depend on the iteration protocol. function* range(n) { for (let i = 0; i < n; ++i) { yield i; } } // looping for (let n of range(10)) { // n takes on the valu...
It is possible to send a value to the generator by passing it to the next() method. function* summer() { let sum = 0, value; while (true) { // receive sent value value = yield; if (value === null) break; // aggregate values sum += value; ...
From within a generator function, the control can be delegated to another generator function using yield*. function* g1() { yield 2; yield 3; yield 4; } function* g2() { yield 1; yield* g1(); yield 5; } var it = g2(); console.log(it.next()); // 1 console.log(it.next())...
A generator is a combination of two things - an Iterator and an Observer. Iterator An iterator is something when invoked returns an iterable. An iterable is something you can iterate upon. From ES6/ES2015 onwards, all collections (Array, Map, Set, WeakMap, WeakSet) conform to the Iterable contract...
Generators are functions which are able to pause and then resume execution. This allows to emulate async functions using external libraries, mainly q or co. Basically it allows to write functions that wait for async results in order to go on: function someAsyncResult() { return Promise.resolve...

Page 1 of 1