Pervy Sage
Pervy Sage

Reputation: 871

What's the difference between 'function foo (callback)' and 'foo(arg1, arg2, function(err,data))'?

I am a beginner to nodejs. I have downloaded the learnyounode module from nodeschool.io and I am trying to do the Make it modular exercise from it. At the end of the exercise they have mentioned this:

Also keep in mind that it is idiomatic to check for errors and do early-returns within callback functions:

function bar (callback) {
  foo(function (err, data) {
    if (err)
      return callback(err) // early return

    // ... no error, continue doing cool things with `data`

    // all went well, call callback with `null` for the error argument

    callback(null, data)
  })
}

Whenever I have tried to understand callback functions they were of the form:

foo(arg1, arg2, function(err,data){
    if(err)
        //Handle it
    //Do something with data
});

I am having a hard time understanding the difference between the two. I google-d for it, but honestly, there were some pages explaining the first callback style while there are some pages explaining the second one. I know that in the second style the function(err, data) is called asynchronously. My understanding by "asynchronously" is that foo is called with arg1 and arg2. When "foo" is completed function(err,data) is called.

However I don't get the function bar (callback) notation. Both of them are doing callbacks then what's the difference between them? Which notation should I use to solve my problem exercise? How do you decide which one to use and when?

Upvotes: 1

Views: 875

Answers (1)

hugomg
hugomg

Reputation: 69944

In foo(arg1, arg2, function(err,data){ You are calling foo and passing it a callback function as one of the parameters. In function foo(callback) you are defining foo and saying that its parameter is a function that you will refer to as "callback".

In a non-async setting you would write something like

//define foo
function foo(arg1, arg2){
    var someData = //...
    return someData;
}

//use foo
var data = foo(1, 2);
console.log(data);

In an async setting, functions call callbacks instead of returning values

//define foo
function fooAsync(arg1, arg2, callback){
    var someData = //...
    callback(someData);
}

and instead of assigning the return value to a variable, we pass a callback where that variable is a parameter:

//use foo
fooAsync(1, 2, function(data){
    console.log(data);
});

We can also pass named functions as callbacks. Passing an anonymous function is just the common case:

function processData(data){
    console.log(data);
}

fooAsync(1, 2, processData);

Upvotes: 4

Related Questions