2

I'm learning Node and I'm coming to grips with the asynchronous nature of it. Now I want to use the async library to perform functions in a series. However, every example looks something like:

async.series([
    function(callback){
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback){
        // do some more stuff ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results){
    // results is now equal to ['one', 'two']
});

So it uses anonymous functions. I would prefer to be able to use pre-defined functions (so I can re-use them without copy-pasting the code). So let's say I have a function defined like:

function doStuff(id){
    alert(id);
}

How can I add this function to the series above? Also, what to do about the task callback in this case?

1 Answer 1

4

Like so...

function doStuff1(callback) {
  console.log('doStuff1');
  callback(null, 'one');
}
function doStuff2(callback) {
  console.log('doStuff2');
  callback(null, 'two');
}
function finally(err, results) {
  // Test error, use results
  // results == ['one', 'two']
}

async.series([doStuff1, doStuff2], finally);
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, but one more sub-question: do I even need a callback in this case? can't I just use function doStuff1(){console.log('dostuff1');}?
Also,, doStuff needs a parameter to be passed to it. How do I do that here?
You must use the callback. If you don't, the execution will stall. The callback is how the async module knows to call the next function in the series.
Using anonymous functions brings with it the benefit of closures for passing variables. It wouldn't be simple to pass a variable to doStuff1(). You could pass a variable from doStuff1() to doStuff2() if you use async.waterfall instead of async.series.
I don't see how you can neatly collect results from each of the doStuff calls to be used at the end of the waterfall without actually passing each result into every subsequent doStuff call, requiring the doStuff functions to pass them along via the callback. Doesn't it just end up with an ever-increasing list of parameters being collected and passed along, muddying the waters along the way? Async seems poorly suited to this kind of workflow.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.