The recent introduction in javascript of generators created a lot of discussions about how to handle asynchronous processing. I recently had a chance to do some actual development with a library I am working on, and solutions using it look very readable. But to me it really gives developers a very interesting concept.

Javascript is not the first language to come up with that concept, Python, .NET, Scala and many others already have it. For example in Scala asynchronous code can be written (from Scala async repository):

import ExecutionContext.Implicits.global
import scala.async.Async.{async, await}

def slowCalcFuture: Future[Int] = ...
def combined: Future[Int] = async {
  await(slowCalcFuture) + await(slowCalcFuture)
}
val x: Int = Await.result(combined, 10.seconds)

The idea is that within an async block one can call the await method on a Future that will quite magically interrupts current processing and resumes once it is fulfilled by returning the future value or throwing its failure. And the async block returns a Future which completes or fails like if synchronous code was written inside, with just enough hints on what is going on under the hood.

I tend to find javascript generators higher level: contrary to async/await in Scala they are not limited to asynchronous computing. Since the user defines its own way of handling values passed to yield, generator functions can be used as an infinite iterator.

Or the higher level function may transform yielded value in a very custom way, for example the generator could yield questions to the user like yield 'What is your name?' and the higher level method asks the question on the page and calls next() with the given answer. This may not be a very smart one, but I hope we will come with smart ideas around the construct.

Handling asynchronous operations is the main use case and there already exist many implementations for this use case, but it is not the only one, let’s tinker around it.