简体   繁体   中英

how to understand callbacks and async.parallel in node

I'm very new to JavaScript and callbacks, so my apologies if this is a stupid question. Based on the async docs for parallel , I came up with this example code that executed the expected way based on the docs:

async = require('async')

async.parallel([
    function(callback){
        setTimeout(function(){
          callback(null, 'one');
        }, 800);
    },
    function(callback){
      setTimeout(function(){
        callback(null, 'two');
      }, 100);
    }
],
    function(err, results){
      console.log(results)
    })       

Running this with node foo.js prints a results array ['one', 'two'] as the docs indicate it will. The thing I don't understand is how exactly this works: when you pass callback as a parameter to each function and then callback is called as callback(null, res) , what exactly is being called her? I've not actually defined any function callback, nor have I passed any sort of operating callback function as a parameter, yet everything magically works fine. Am I totally missing the point here? Or is this actually the under-the-hood magic of async ?

You are not the one passing callback to the task functions, the async module is . It's a special function that the module passes to your task functions that when called, checks if any more tasks are left.

Here is something similar to what is being done inside async :

function myParallel(tasks, finalcb) {
  var tasksLeft = tasks.length,
      results = [],
      ignore = false;

  function callback(err, result) {
    if (ignore) return;
    if (err) {
      ignore = true;
      finalcb && finalcb(err);
    } else if (--tasksLeft === 0) {
      ignore = true;
      finalcb && finalcb(null, results);
    } else
      results.push(result);
  }

  tasks.forEach(function(taskfn) {
    taskfn(callback);
  });
}

myParallel([
  function(callback) {
    setTimeout(function() {
      callback(null, 'one');
    }, 800);
  },
  function(callback) {
    setTimeout(function() {
      callback(null, 'two');
    }, 100);
  }
], function(err, results){
  console.log(results)
});

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