a blog for those who code

Thursday 5 November 2015

Simplified Control Flow in Node.js

In this post we will be discussing about Step which is a focused utility module that enables simplified control flow for serial and parallel execution. According to Step, it is a simple control-flow library for Node.js that makes parallel execution, serial execution and error handling painless.

Install

npm install step

Usage

To use Step for serial execution what you need to do is to wrap your asynchronous function calls within functions that are then passed as parameters to this object. For example in the below code we are using Step to read the data and show the contents.

var Step = require('step');
var fs = require('fs')

Step(
  function read() {
    fs.readFile('example.txt', 'utf8', this);
  },
  function show(err, text) {
    console.log(text);
  }
);

In the above code, first function in the Step sequence will read the data using asynchronous function (fs.readFile) which is then passed to a second function. We pass 'this' as the callback to fs.readFile. When reading the file will complete it will sent the results as the arguments to the next function in the chain. In the second function, we are showing the string of the file.

To use Step for parallel execution what you need to do is to wrap your asynchronous function calls within functions and then passed this.parallel() as the last parameter to this object. The results in a parallel being passed to the next function for each of the readFile in the first function.

var Step = require('step');
var fs = require('fs')

Step(
  function read() {
    fs.readFile('example.txt', 'utf8', this.parallel());
    fs.readFile('file.txt', 'utf8', this.parallel());
  },
  function show(err, text1, text2) {
    console.log(text1);
    console.log(text2);
  }
);

Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.

1 comment:

  1. I prefer using npm.im/async for all tasks that required flow control.

    ReplyDelete