Tuesday, April 1, 2014

Thunks and co with ES6 generators

A thunk is the output of a transformed node.js-style asynchronous function. The transformed function (aka the thunkified function) is meant to work with a generator wrapper. Here is the generator wrapper I am talking about:
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: As you can see this is very different from how you would need to do it with the async module. For example, you can directly use the array subscript 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: