Sunday, March 31, 2013

Node.js: Sync vs. Async

node.js is becoming very popular,
and it is very different than a typical web server programming

Here is adjusted example from excellent video training
(that also requires you to type, since samples are not provided):
Learning Node.js LiveLessons (Sneak Peek Video Training): O'Reilly - Safari Books Online:

JavaScript is single-threaded, and node.js processing is like Windows 3.1 or 95:
"collaborative multitasking".
And there is a big difference: APIs are asynchronous.
This, along with lack of a good IDE (intellisense), comes with "cost" in productivity.


Here is a simple example of synchronous getting list of sub-directories:
function load_albums_sync(callback){
  var folder='albums';
  var file_list = fs.readdirSync(folder);
  var dirs_only=[];
  for(var i=0;i<file_list.length;i++) {
    var st=fs.statSync(folder+'\\'+file_list[i]);
    if(st.isDirectory())
      dirs_only.push(file_list[i]);
  }
  callback(null,dirs_only);
}

JavaScript Async require separating requrests from responses:
function load_album_async(callback){
  var folder='albums';
  fs.readdir(folder,function(err,file_list){
    if(err){
      callback(err);
      return;
    }
    var dirs_only=[];
    (function iterator(i){
      if(i>=file_list.length){
        callback(null,dirs_only); // done
        return;
      }
      fs.stat(folder+'\\'+file_list[i],function(err,stats){
        if(err){
          callback(err);
          return;
        }
        if(stats.isDirectory())
          dirs_only.push(file_list[i]);
        iterator(i+1);
      });
    })(0);
  });
}

Manageable, but with with nested functions and brackets, is cryptic almost as Lisp.

Observe that testing each item in the directory requires recursion,
since every item needs to be tested asynchronously:
start, and provide callback function to handle responses.

Async is not free.

Maybe Anders Hejlsberg, creator of C# and TypeScript (pre-processor for JavaScript),
can now add async-await from C# to to TypeScript,
and simplify JavaScrypt async programming also.

No comments: