-
Notifications
You must be signed in to change notification settings - Fork 0
NodeJsApi
l8 tasks are a tool to reverse the "Inversion Of Control" that happens when the code of a function is called due to some event instead of being called in an imperative procedural way. l8 tasks turn callbacks back to regular calls.
fs = require( "fs" );
fs.readFile( "message.txt", "utf8", function( err, rslt ){
console.log( "Content: " + rslt );
})
With l8 tasks, there is no callbacks, there are steps instead.
l8.step( function( ){ l8.require( "fs" );
}).step( function( fs ){ fs.readFile( "message.txt", "utf8" );
}).step( function( ct ){ console.log( "Content: " + ct ); })
The full node.js API is available using l8.require()
With l8 tasks, because there is no callbacks, errors are processed differently. There are two solutions, one is similar to the exception handling done in javascript with try/catch, the other one is similar to the error handling done in the Go language with functions returning [err,rslt].
l8.step( function( ){ l8.require( "fs" );
}).step( function( fs ){ l8.begin
.step( function( ){ fs.readFile( "message.txt", "utf8" );
}).failure( function( e ){ return "recover";
}).end
}).step( function( ct ){ console.log( "Content: " + ct ); })
On error, "recover" will be shown. That was the try/catch style. Now the "go" style:
l8.step( function( ){ l8.require( "fs" );
}).step( function( fs ){ fs.readFile.go( "message.txt", "utf8" );
}).step( function( e, r ){ console.log( "Content: " + (e ? "recover" : r ); })
Please note the .go suffix attached to readFile. The "Go" style, this may come as a surprise, is somehow simpler.
There is yet another style to invoke the node.js API, it is the "promise" style.
l8.require.promise( "fs" )
.then( function( fs ){ fs.readFile.promise( "message.txt", "utf8" ) })
.then(
function( ct ){ console.log( "Content: " + ct; },
function( e ){ console.log( "Content: recover"; }
)
Because l8.promise() is asynchronous, whereas node.js native require() is synchronous, l8.promise() can be used to access the node.js API from the browser (this requires http access to a node.js API server). In that situation, be careful when invoking "new" because the new object is not available immediately, in a synchronous manner, it is available for the next step or as a promise (when using some_class.new.promise( ... )). There is an example about in the examples chapter.