简体   繁体   中英

Using Node.js async.series without anonymous functions

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM