Additional methods available to generators : throw and return
- throw : log an error
- return : overwrites the value
Code
//Generators in ES6 - Additional arguments available to generators
//throw()
let obj = {
[Symbol.iterator]: gen
}
function *gen(end){
for (let i = 0; i < end; i++) {
try {
yield i;
} catch (e) {
console.log(e)
}
}
}
let it = gen(2);
console.log(it.next());
console.log(it.throw('There was an error'));
console.log(it.next());
console.log(it.next());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//Generators in ES6 - Additional arguments available to generators
//return()
let obj = {
[Symbol.iterator]: gen
}
function *gen(end){
for (let i = 0; i < end; i++) {
try {
yield i;
} catch (e) {
console.log(e)
}
}
}
let it = gen(2);
console.log(it.next());
console.log(it.return('There was an error'));
console.log(it.next());
console.log(it.next());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25