Fluent asynchronous API 5: internally calling methods

One more thing about fluent asynchronous APIs… Because synchronous methods are changed into asynchronous ones by the flasync helper, internal calls of a synchronous method would in principle also have to be asynchronous calls. That would go against the requirements that I’ve set in the first post to provide a way for API authors to write code that is as close as possible to what they would write in a regular API.

For this reason, I recommend that API authors store a private version of all their methods. This can be achieved as follows:

this.write = this.asyncify(
this._write = function(text) {

Console.log(text);
return this;
});

Both asynchronous and synchronous methods, when they need to call another synchronous method, should use that private synchronous version:

this.fromFile = this.async(
this _fromFile = function(path, next) {

fs.readFile(path, function (err, text) {
if (err) throw err;
self._write(text);
next();
});
return this;
});

The asynchronous method calls the non-asynchronified private version of write, to avoid wasteful and unclear asynchronous calls to a method that does not require to be called asynchronously. Synchronous methods that need to call other synchronous methods should do the same. Internally, methods should always call the private synchronous versions of synchronous methods.

What about asynchronous methods then? Well, it’s the same idea. You’ll want the asynchronous method code to use private versions of the methods it calls, including asynchronous ones:

this.fromFileWithFileName = this.async(
this._fromFileWithFileName = function(path, next) {

this
._write(path)
._fromFile(path, next);
return this;
});

Finally, I have to write a word about synchronous methods calling asynchronous ones: well, there’s no such thing. If a method’s code calls asynchronous code, it becomes asynchronous and needs to be written as such.

No Comments