co(function*(){
...alot of synchronous looking code...
})()
That generator wrapper takes the output of a thunkified async function call in a yield context and passes the ultimate results of the async call back to the original yield location; so code like this works (within the generator wrapper):output = yield thunkfiedAsyncFn(args...)
Where node.js asynchronous functions are called with a few arguments plus one callback function to receive the output of the async operation, a thunkified node.js function call takes the original arguments MINUS the callbcak function and outputs a thunk function. In the above example what you are yielding to the generator wrapper is the thunk function.
Here is a full example of reading a list of files in series:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node --harmony-generators | |
var fs = require('fs') | |
, thunkify = require('thunkify') | |
, co = require('co') | |
, readFile = thunkify(fs.readFile) | |
, fns = ["file0.txt", "file1.txt" | |
, "file2.txt", "file3.txt"] | |
co(function*(){ | |
var contents = '', i | |
for (i=0; i<fns.length; i+=1) { | |
contents += yield readFile(fns[i]) | |
} | |
console.log(contents) | |
})() |
i
of the fns
array (normally you have to worry about the closure over i
in a callback always being equal to 4.
To do the same async work in parallel you collect an array of thunk functions and yield
that array. Example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node --harmony-generators | |
var fs = require('fs') | |
, thunkify = require('thunkify') | |
, co = require('co') | |
, readFile = thunkify(fs.readFile) | |
, fns = ["file0.txt", "file1.txt" | |
, "file2.txt", "file3.txt"] | |
co(function*(){ | |
var contents, thunks | |
thunks = fns.map(function(fn){ | |
return readFile(fn) | |
}) | |
contents = (yield thunks).join('') | |
console.log(contents) | |
})() |