0

As iam exploring Nodejs,i need to know what's a callback?.Can anybody help me.Since i have referred many blogs and tutorials.But still iam not clear.Can anybody explain with simple example and refer forums related to this.

Thanks

2 Answers2

0

A callback is just a function that you call when an action has taken place. For example:

var myCallback = function(){
        console.log("Callback Run");
    };

setTimeout(myCallback, 1000);

Callbacks are typically used in asynchronous code (such as Ajax calls). The code is passed a function to run when it completes, such as this jQuery:

var doAnAjaxCall = function(success_callback, fail_callback){
       $.ajax({
           url: 'test.html',
           success: function(data){
               data.date = new Date(data.date);
               callback(data);
           },
           fail: fail_callback
       });
   },
   okCallback = function(data){
       console.log(data.date);
   },
   failCallback = function(){
       console.error(arguments);
   };

doAnAjaxCall(okCallback, failCallback);
eckymad
  • 1,032
  • 8
  • 6
0

A very simple example can be:

function sum (a, b, callback) {
  callback (a + b);
}

You can call the function sumin this way:

sum (1, 1, function (res) {
  console.log ('Result of the sum is ' + res);
}

As you can see from the code above, the actual parameters are:

  • a = 1
  • b = 2
  • callback: function (res) { ... }
marco
  • 51
  • 3
  • i have one doubt,even if am assinging callback to the varible ,also it works.,for e.g: var app = require('express'); var sample = function(a,b,callback){ var b = callback(a+b); } sample(1,2,function(res){ console.log("Result of the sum is:", +res); }); – user4223185 Jan 05 '16 at 13:05
  • This [thread](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) could clarify your doubt. – marco Jan 05 '16 at 13:26