Summary

This document provides an introduction to JavaScript generators. It covers various aspects, from basic concepts to advanced applications and includes code examples.

Full Transcript

Midterm Review Midterm The midterm results are visible We can have a discussion if you like. Generators in JavaScript CPEN320 Outline What are generators ? Creating a simple generator Iterating with a generator Combining generators with promises What is a generator ? What is a gen...

Midterm Review Midterm The midterm results are visible We can have a discussion if you like. Generators in JavaScript CPEN320 Outline What are generators ? Creating a simple generator Iterating with a generator Combining generators with promises What is a generator ? What is a generator ? A feature (introduced in ES6) that allows a function to generate a sequence of values over time, pausing and resuming its execution, instead of computing them all at once. Used to “remember” state of the function at the point where it left off. Allows us to control the function’s execution and its returned values. Useful when you want to create iterators or handle asynchronous programming in a more flexible way. Enter generators This is achieved using a new kind of function called a generator function, which is declared using the function* syntax (note the asterisk after the function keyword) and the yield keyword inside its body. function* simpleGenerator() { yield alert(1) } Yield and done ‘yield’ pauses the execution at that point, and resumes the execution on a subsequent call to the generator. Yield can also return a value to the caller - typically value being iterated on. When end of function is reached, it returns ‘undefined’ (can also specify a return) value, and the generator is DONE. Cannot be resumed after that point ever. function* simpleGenerator() { yield alert(1) yield alert(2) } Yield First time the next is called: executes until a ‘yield’ is encountered - Control is then ceded back to the caller function (but state is remembered) Each subsequent call to the yield resumes execution from after where the first ‘yield’ left off, and executes until the next yield statement (state is remembered), or a return statement or throw occurs in the function (the generator is terminated) IMPORTANT: Yield can only be called within generator function itself, not even in nested functions or from asynchronous callbacks. Value returned by yield Yield returns an object called IteratorResult consisting of two properties: 1. value: represents the actual value returned by the yield statement 2. done: a boolean flag representing whether or not the iteration is finished It’s caller’s responsibility to check value of ‘done’. In addition, the generator can a. Throw an exception - this can be caught via a try-catch statement b. Return a value (using ‘return’) - sets the value of IteratorResult to value and the done property to true. Note that not returning a value will still set the done property to true and the value to ‘undefined’ SimpleGenerator function* simpleGenerator() { yield 1 yield 2 yield 3 } const g = simpleGenerator(); console.log(g.next()); ? SimpleGenerator function* simpleGenerator() { yield 1 yield 2 yield 3 } const g = simpleGenerator(); console.log(g.next()); // { value: 1, done: false } console.log(g.next()); ? SimpleGenerator function* simpleGenerator() { yield 1 yield 2 yield 3 } const g = simpleGenerator(); console.log(g.next()); // { value: 1, done: false } console.log(g.next()); // { value: 2, done: false } console.log(g.next()); ? SimpleGenerator function* simpleGenerator() { yield 1 yield 2 yield 3 } const g = simpleGenerator(); console.log(g.next()); // { value: 1, done: false } console.log(g.next()); // { value: 2, done: false } console.log(g.next()); // { value: 3, done: false } console.log(g.next()); ??? SimpleGenerator function* simpleGenerator() { yield 1 yield 2 yield 3 } const g = simpleGenerator(); console.log(g.next()); // { value: 1, done: false } console.log(g.next()); // { value: 2, done: false } console.log(g.next()); // { value: 3, done: false } console.log(g.next()); // { value: undefined, done: true } Using yield to handle async flows function* fetchData() { const user = yield fetch('https://api.example.com/user’); const posts = yield fetch(`https://api.example.com/posts?user=${user.id}`); return posts; } Use Cases (Iteration) function* generateID() { let id = 1 while(true) { yield id id++ } } const g = generateID(); console.log(g.next()); // 1 console.log(g.next()); // 2 … Class activity - 1 Write a simple generator function to yield the factors of a natural number n (including itself) The function takes as input n and only calculates the factors on demand and not ahead of time (one at a time). You can assume that the input has been validated already. Solution function* factors(n) { for (let i = 1; i

Use Quizgecko on...
Browser
Browser