Generators are functions which don’t necessarily run to the end upon execution. Instead, upon each call they yield a value. A generator is created by adding an asterisk in front of the function name.
::TIP Generators : A function which yeilds certain values, and stops at a certain point ::
Table Of Contents
Topic Focus
Description
- By running generators you actually get back an iterator
- You might use generators for a asyncronous function for instance, if you return something from the server, and wanted to yield the results. After you can do something with the results with your iterator
Code
When executing a function they don’t return a value immediately, instead an iterator is returned. This iterator may then be used to access the returned values step by step.
//Generators in ES6
function *select() {
yield 'House';
yield 'Garage';
}
let itTest = select();
console.log(itTest.next());
console.log(itTest.next());
console.log(itTest.next());
console.log(itTest.next());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Generators in ES6
let obj = {
[Symbol.iterator]: gen
}
function *gen(){
yield 1;
yield 2;
}
for (let element of obj) {
console.log(element);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14