How does nimble work in nodejs?

1.2k views Asked by At

i am trying to understand how to use nimble for flow control with nodejs but I am having trouble understanding how it actually works and there's really no documentation that explains it(that I could find)

For example, take this code from the docs:

_.parallel([
    function (callback) {
        setTimeout(function () {
            console.log('one');
            callback();
        }, 25);
    },
    function (callback) {
        setTimeout(function () {
            console.log('two');
            callback();
        }, 0);
    }
]);

I am having trouble understanding the callback argument that the functions take, what actually gets passed as a callback? The next function in line? If that is the case, then why does the second(and last) function also run callback()? If there is no more functions to run then what is the point of this? Thanks!

I did my own little test and took out the callbacks:

var flow = require('nimble');

flow.parallel([
function() {
    setTimeout(function() {
        console.log('this happens');
    }, 3000);
},
    function() {
        setTimeout(function() {
        console.log('and this happens at the same time');
    }, 3000);
}
]);

And the code works the same as if I had callbacks passed in, so now I feel likeI really don't understand what the callback args do.

2

There are 2 answers

1
mpm On

I am having trouble understanding the callback argument that the functions take, what actually gets passed as a callback?

The callback is here to acknowledge the fact that the async operation is finished. You dont need to know what the callback does , only what it accepts as arguments.

it's called continuation passing. => given a function , and a callback as argument , the callback once executed will "continue" what whatever is in charge of the control flow was doing.

You might eventually pass an error object to the callback as first argument to yield an error if the async operation is unsuccessfull. You might want to look at the async package on npm for further explainations on the matter.

0
PET_Maya On

In serial flow control executing a number of asynchronous tasks in sequence we use "callbacks". one such example setTimeout function for repeatedly executing the same setTimeout function set out for various executions (asynchronous tasks in sequence)one after the other needs close attention on the code execution. For the above situation one can use flow-control tool such as Nimble (npm install nimble)that makes life easy that provides an array of functions for Nimble to execute, very neatly one after the other.