Stop Using Generators for Asynchronous Code

I cringe every time I see a new library like co or redux-saga that abuses generators in an effort to improve “callback-hell.”

The basic idea is that instead of writing a regular function, you write a generator, and inside the generator you yield a promise when you want to do something asynchronous. The library then waits for the promise to resolve and then returns execution back to your generator function.

But it seems to me that using generators for handling asynchronous tasks is backwards. The purpose of a generator is to create an iterator — not to handle async tasks.

Here’s the deal. If you’re using generators (or React), you’re probably already using babel anyway to get that functionality. And if you’re using babel, you might as well use the new async/await syntax, which is not that much different and is much easier to read. If that’s the case, please do so.

It may be argued that babel implements async/await using generators, but I don’t believe that will always be the case. See kneden, for example, which is a new (but not yet complete) babel plugin that generates significantly better transpiled code than the current implementation.

If you enjoyed this post or found it useful, please click the ♥ button below so that more people can see it!