jdonaldson/promhx — pull request #36 by Blank101 (2014-10-02 19:10:18+00:00)
Title: Added automatic promisification of NodeJS style functions

This addition is a starting point for automatically "promisifying" NodeJS style functions using macros. This is similar to the way it is done in the popular bluebird promise library for JS: https://github.com/petkaantonov/bluebird/blob/master/API.md#promisification

Without getting into details this will convert a function with signature of the form:

function (a1:Type1, a2:Type2, ..., callbackFunc:String -> returnType:SomeType):Void;

into:

function (a1:Type1, a2:Type2, ...):Promise;

Here is an example with node fs using the https://github.com/dionjwa/nodejs-std externs library:

var readFile = promhx.js.NodeTools.promisify(cast(Node.require("fs"), js.Node.NodeFS).readFile);
readFile("someFile.txt", { encoding:'utf8' } ).then(function (data) {
trace(data);
});

I also included a build function which will scan through a definition file (such as the ones included in the above library) and build all the fields that can be promisified.

@:build(promhx.js.NodeTools.autoPromisify("js.Node.NodeFS", "fs"))
class NodeFSProm {
}

// Somewhere else in the code
NodeFSProm.readFile("someFile.txt", { encoding:'utf8' } ).then(function (data) {
trace(data);
});

Some notes:

* I tried to put the NodeTools in the js.promhx package, but I get js package unavailable errors from the macro context. You may want to consider renaming this directory for consistancy.
* If a function signature has more than one return type in the callback then the promise will return an array of values typed as Array.