Friday, February 17, 2017

CallBack function in node.js



  • A callback function is another function that is usually passed as an argument to another function and is usually invoked after a particular event.
  • Asynchronous equivalent for a function
  • Node makes heavy use of callbacks
  • All the APIs of Node are written in such a way that they support callbacks.

Simple example of callback

console.log("User 1 made a request");
setTimeout(callback,5000)
console.log("User 2 made a request");
setTimeout(callback,5000)
console.log("User 3 made a request");
setTimeout(callback,5000)

function callback(){
    console.log("Queried the database and delivered data in 5 seconds")
}

Output
c:\Development\NodeProjects\vanilanode>node callback
User 1 made a request
User 2 made a request
User 3 made a request
Queried the database and delivered data in 5 seconds
Queried the database and delivered data in 5 seconds
Queried the database and delivered data in 5 seconds

c:\Development\NodeProjects\vanilanode>

Another example for callback
//Function callback
function fnCallback(list)
{
    var newList =[];
    for(var i=0;i<=list.length;i++)
    {
        if(list[i] <5)
        {
            //add to the new list
            newList.push(list[i])
        }
    }
    return newList;
}
//callback
function filter(list,fnCallback)
{
    return fnCallback(list);
}

var filtered = filter(list,fnCallback);
console.log(filtered);

No comments:

Post a Comment