0

When I tried to find the definition of Callback, I could find bunches of information, but the problem was that they were not uniform, but rather different.

One of the definitions I faced most of the times was that, Callback is just a function that is passed as an argument in higher order function. e.g.

 function higherOrderFunction(callback, otherArguements){
      // do some stuffs
      callback();
 }

And the next most frequent was that 'Callback' is a function that is executed after a particular function is finished.

Here, I am so confused. First definition is about the format(or rule), while the second one is rather about the purpose. Well it can be a possibility that these two are so tightly connected. But I can't find the connection yet and why this connection are inevitable.

And also, as a counter-example, for the second definition in terms of the first one, I can write a function like below.

e.g.

 function higherOrderFunction(callback, otherArguements){
     callback();
     // do some stuffs later! 
 }

Then, the callback is passed as an argument, but it's going to be executed before other stuffs, not before other things are finished.

So, I'm so confused here. What is the rigorous, exact definition of "Callback"?

Now.Zero
  • 1,147
  • 1
  • 12
  • 23
  • Possible duplicate of [What is a callback function?](https://stackoverflow.com/questions/824234/what-is-a-callback-function) – Mzq Feb 15 '19 at 11:03

1 Answers1

0

There is not much benefit of using callback() if you just want to do something before the higherOrderFunction.

Most of the callbacks are used to get results from another async call/process, i.e.

function callback(err, rows){
    if (err) {
        console.log(err);
        return null;
    } else { 
        return rows;
    }
}

function queryDB(callback, sql){
    // Do the database suff
    callback(err, rows);
}

By using a callback, you avoid the problem of waiting/racing, i.e.

var IneedResultsFromDatabase=queryDB("some SQL");
//But you need to wait [I don't know how many] seconds before I get a result.
print(IneedResultsFromDatabase);//gives you undefined

The correct way is using a callback (javascript example):

var data=queryDB(callback, sql);

So by default, it waits until you get a result, or log the error and return null.

Mzq
  • 1,796
  • 4
  • 30
  • 65