Callback Simplified

We all developers wants to have a taste of Node.Js, but that doesn’t come so easily. One say that World of Node.Js is a world of callbacks.


Picture

An owl staring right onto you. It’s constantly watching you, as if its waiting for an event to happen. Similarly callbacks are functions passed as parameters waiting for called function to call it.

var prey = function(input, callback) {
var output = input + ‘ Eat’;

//Doing some operations
console.log(‘Analysis ‘, input);
callback(output);//callback is called
}
var main = function() {
console.log(‘This is Owly!’);
 prey(‘Prey’, function(params) {
console.log(params);
});
console.log(‘I\’m full know’);
};
main();
/* logs:
* This is Owly!
* Analysis Prey
* Prey Eat
* I’m full know
*/

Above is a simple callback function, but its the base of all. You might come across multi-level callbacks but all work the same.

Truth

Custom Callback functions are synchronous in nature. If you won’t believe me just see below:

//Synchronous blocking operation 
var databaseOperationSync = function(query, callback) {
var v = ‘JavaScript Sync’ + query;
callback(v);
}
var main = function() {
console.log('Main Block Enter');

databaseOperationSync("Asynchronous", function(p) {
console.log('Response: ', p);
});
 console.log('Main Block Exit');
};
main();
/* output:
* Main Block Enter
* Response JavaScript Synchronous
* Main Block Exit
*/

By now it must be clear to you. But how come node.js have asynchronous functions then. For that you have to get a bit deep into Asynchronous Callbacks

Thanks reading!