简体   繁体   中英

how does the callback in async.parallel work (where does it come from?)

I found this example in the docs . I understand how the main callback (function (err,results)...) works but what is the 'callback' parameter that is passed into one and two functions? Where are those coming from and what do they do?

async.parallel({
    one: function(callback){
        setTimeout(function(){
            callback(null, 1);
        }, 200);
    },
    two: function(callback){
        setTimeout(function(){
            callback(null, 2);
        }, 100);
    }
},
function(err, results) {
    // results is now equals to: {one: 1, two: 2}
});

The callback argument is passed to your functions by the async infrastructure. It points to a function inside of async (though that's not something you need to know). The async infrastructure passes it to you and asks you to call it at the right time.

This is how you communicate back to the async library to tell it that your async function has finished its work and also whether it finished successfully or with an error. When your function finishes it's work, you call that function and that notifies the async library that this step of the process is now done (with either error or success).


FYI, if you're familiar with Express middleware in node.js, it's very similar to the next argument that is passed to middleware. When your middleware gets called, one of the arguments passed to it is the next callback. Your middleware does its work (which could be async) and then when it's done, it tells the Express infrastructure that it's done by calling the next() callback that was passed to it.

Here's a somewhat similar example from Express:

app.use(function (req, res, next) {
  doSomethingAsync(function() {
       next();
  })
});

It doesn't come from anywhere, its just how the library works, a callback is used to pass data to the next function.

This is the function here:

function _parallel(eachfn, tasks, callback) {
    callback = callback || noop;
    var results = isArrayLike(tasks) ? [] : {};

    eachfn(tasks, function (task, key, callback) {
        task(rest(function (err, args) {
            if (args.length <= 1) {
                args = args[0];
            }
            results[key] = args;
            callback(err);
        }));
    }, function (err) {
        callback(err, results);
    });
}

https://github.com/caolan/async/blob/master/dist/async.js#L3471

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