Koa uses co under the hood,
so to fully understand how Koa works,
you must understand co.

Co uses ES6 generators.
You can tell if a function is a generator if it has a star:

  1. function* () {
  2. }

yield is a keyword specific to generators and allows users to arbitrarily suspend functions at any yield point.
yield is not a magical async function - co does all that magic behind the scenes.

You can think of co‘s use of generators like this with node callbacks:

  1. function* () {
  2. var val = yield /* breakpoint */ function (next) {
  3. // #pause at the break point
  4. // execute an asynchronous function
  5. setTimeout(function () {
  6. // return the value node.js callback-style
  7. next(null, 1);
  8. }, 100);
  9. }
  10. assert(val === 1);
  11. }

This workshop will not cover all the intricacies of generators as that alone would
be its own workshop, and most people (including myself) wouldn’t be able
to understand generators in less than a day.

Yieldables

You can only yield a few types of “async” things in Co. We call these “yieldables”.:

Thunks

Thunks are asynchronous functions that only allow a callback:

  1. function (done) {
  2. setTimeout(function () {
  3. done(/* error: */ null, true);
  4. }, 100)
  5. }

If there are additional arguments on this function,
a neat trick is to simply wrap it in a thunk or return a thunk.
You may be interested in thunkify,
but we will learn how to “thunkify” node.js-style callbacks in this exercise.

Promises

We won’t show you how to write code with promises,
but you can yield them!

Creating yieldables

In this exercise, we will learn how to create “yieldables” from callbacks.
We will not go into depth of how generators and co works as it is unnecessary for Koa.

Learning more