Koa is based on generators which are a new feature in ES6. The syntax for a generator is function* fnName() {}
where fnName
is optional, just as with normal functions. What generators allow one to do is effectively to suspend execution and hand over the execution flow to the calling function, which can then inject data into the generator. This is exploited to make async calls seem sync. Example:
function *() {
var data = yield db.find(); //yield suspends execution and hands over the control flow
data.map(someMapper);
}
As you can see we can pretend the async function db.find
is sync, because the caller takes care of executing the function for us and can inject the response into the variable data. That's the high level overview of generators. How they actually work is another story but nothing you need to worry about at first. ES6 (also known as Harmony) features are not enabled by default so when running node, use the harmony flag: node --harmony index.js