Created: 2011-07-17 11:52
Updated: 2018-06-14 13:55
License: mit


GoWithTheFlow.js - a javascript flow control micro library

GoWithTheFlow.js is a javascript asynchronous flow-control micro library which works in node.js and in browser. It allows controlling how your asynchronous code is executed, that is, sequentially or in parallel. Flow() is only 30 lines long!

How to use it

Let's start with a basic example: 2 jobs ran in sequence. The first job is a timeout hence the result is delivered asynchronously; the second job is to be ran only after completion of the first job.

var Flow = require('gowiththeflow')
    console.log("step 1: started, it will last 1sec");
        console.log("step 1: 1sec expired. Step 1 completed");
    }, 1000);
    console.log("step 2: run after step1 has been completed");

It will display the following

step 1: started, it will last 1sec
step 1: 1sec expired. Step 1 completed
step 2: run after step1 has been completed


In order to keep it as simple as possible, Flow has only 2 methods.

.seq(callback) to execute job sequentially

.seq() is used to execute functions sequentially. The callback parameter will be executed only after all previous jobs are completed. The callback signature is callback(next, error, result)

  • next(error, result) is the function to call when the job is completed. error is to notify an error to the next job. result to notify a result. error and result may be omitted, if so they are considered equal to undefined

  • error is the error send by the previous jobs

  • result is the result send by the previous jobs

for example

        console.log("first job");
        console.log("second job. run *after* first job");

.par(callback) to execute job in parallel

.par() is used to execute functions in parallel. The callback parameter is the same as for .seq(). If multiple .par() are declared one after another, they are run in parallel. The first .seq() after them will receive all the error and result in an Array, one array item per previous .par()

for example

        console.log("job foo");
        next(null, "foo");
        console.log("job bar");
        next(null, "bar");
    }).seq(function(next, errors, results){
        console.log("job run *after* the completion of foo and bar");
        console.assert(errors.length == 2 && errors[0] === null && errors[1] == null)
        console.assert(results.length == 2 && results[0] === 'foo' && results[1] == 'bar')

That's it!


GoWithTheFlow.js is available on github here under MIT license. If you hit bugs, fill issues on github.

Feel free to fork, modify and have fun with it :)

Cookies help us deliver our services. By using our services, you agree to our use of cookies Learn more