0

I saw a code that looks like this (Pro Node). It uses async library.

var async = require("async");
async.series([
  function(callback) {
    setTimeout(function() {
      console.log("Task 1");
      callback(null, 1);
}, 300); },
  function(callback) {
    setTimeout(function() {
      console.log("Task 2");
      callback(null, 2);
    }, 200);
  },
  function(callback) {
    setTimeout(function() {
      console.log("Task 3");
      callback(null, 3);
}, 100); }
], function(error, results) {
  console.log(results);
});

When I run it, it shows:

Task 1
Task 2
Task 3
[ 1, 2, 3 ]

All is well - however, I do not quite understand what the callback lines are: callback(null, 1), callback(null, 2), and callback(null, 3).

If I remove all of those lines, when I run the code it returns only:

Task 1

What do the first and second arguments do and why are the second arguments 1, 2, and 3?

Iggy
  • 5,129
  • 12
  • 53
  • 87
  • Do you know what callbacks are without async.js? Do you know how callbacks in the native node functions work? – Bergi Oct 13 '17 at 03:05
  • @Bergi, I am not familiar. I used callbacks in the past when with `fetch`, but I haven't explored it. I wasn't sure if this is an async thing or broader javascript thing. – Iggy Oct 13 '17 at 04:16
  • In that case, you'll want to read a more generic tutorial first - there are dozens out there on how callbacks work in nodejs - e.g. [this one](https://eloquentjavascript.net/20_node.html). For information about why node callbacks have two parameters, see [this question](https://stackoverflow.com/q/40511513/1048572) – Bergi Oct 13 '17 at 04:29

1 Answers1

1

In the async library, calling the callback function of async.series runs the next function in the array. The first parameter is any error data. It's a node convention that any errors are the first parameter to callback functions. The second parameter is the success data, and is passed to the 2nd parameter of the async.series callback as an array of all success data.

See this answer for more details as to why node prefers error first callbacks.

Steven Lambert
  • 5,571
  • 2
  • 29
  • 46
  • Awesome. So the first argument = error, and the second is what it returns. Very clear - I understand it now. Thank you so very much!! – Iggy Oct 13 '17 at 04:24