It has to be rather simple, but I can't understand the solution for the beginning exercise from koa workshop.
The test:
var co = require('co');
var assert = require('assert');
var fs = require('./index.js');
describe('.stats()', function () {
it('should stat this file', co(function* () {
var stats = yield fs.stat(__filename);
assert.ok(stats.size);
}));
});
The solution and the task:
var fs = require('fs');
/**
* Create a yieldable version of `fs.stat()`:
*
* app.use(function* () {
* var stats = yield exports.stat(__filename);
* })
*
* Hint: you can return a yieldable.
*/
exports.stat = function (filename) {
return function (done) {
fs.stat(filename, done);
}
};
The way I think of this test is: co
library runs the generator function for us, the fs.stat(__filename)
invokes, returns the
function (done) {
fs.stat(filename, done);
}
Then, all I have are questions: why does anonymous function returns fs.stat()
at the same place and where does it take done
callback? I have logged this callback out, it's generators next()
method with stats
object as a passing parameter, but I can't find any information about callbacks injection in co
. How does this work? Thank you in advance.