Generator Functions in Javascript

We will be building on what we discussed in previous post generator-functions-using-co

Here we will focus on how to implement something analogous to co. i.e. actually implement an iterable.

How to run the function*

Steps involved in running through a generator function. If its a bit confusing, it will be clear when we look at the implementation.

  1. we first invoke the function and store it in a variable.
  2. The invocation of the function returns an iterable object back to us.
  3. We can call ‘next‘ on this object to take us to the first yield point in the function.
  4. this call will give us back an object with the properties of value and done
  5. we can continue iterating through this until we are done or stop at any point


function* foo(){
    let x = yield 'Please give mea value for x'

    let y = yield 'Please give mea value for y'

    let z = yield 'Please give mea value for z'

    return (x+y+z)

let generatingFoo = foo()
//return an iterable object stored in generating foo
//{value: 'Please guve me a value for x', done: false} the result you pass in into x
//{value: 'Please guve me a value for y', done: false} the result you pass in into y
//{value: 'Please guve me a value for z', done: false} the result you pass in into z
//{value: 50, done: true}

So, with the basic understanding of a generator out of the way,  here is the same code implemented in previous post but using a function called iter that shows the implementation of the iterable

function iter(generator){
 const iterator = generator()
 function iterate(iteration){
   return iteration.value
  const promise = iteration.value
  return promise.then(x => iterate(
 return iterate(

iter(function *(){
    const url = ''
    const response = yield fetch(url)
    const post = yield response.json()
    const title = post.title
    console.log('Title:', title)
.catch(error=> console.error(error.stack))
.then(x => console.log('iter resulted in ', x))




No Comments

You can leave the first : )

Leave a Reply

Your email address will not be published. Required fields are marked *