#
Node.js Callback
This tutorial explains to you the concept of Node.js Callback. This article will show you an example as well.
In ASYNCHRONOUS programming, in many cases we need to execute something when a function/ procedure completes. This is a case we need to use a Callback function in Node.js.
Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.
The code is not automatically ASYNC, but you can use Promises, Observables and ASYNC functions (already defined) in order to write ASYNC code.
However, the Callback concept is not related to the ASYNCHRONOUS programming, but it is very used in ASYNC programming. The Callback concept is related to the Continuation-Passing Style (CPS) as opposite to the Direct Style. With CPS, function invokes a callback (a function usually passed as the last argument) to continue the program once it has finished. This concept is important in ASYNC programming, but can be used technically in SYNCHRONOUS programming as well (even if it is not a good practice).
Here it is how a Callback can be used in Node.js (example):
//This is a Callback function definition //
var myCallback = function cb(data) {
console.log('CB has finished// data='+data);
//return y;
}
function f1() {
console.log('F1 is running ...');
let y = 0;
for(var i = 0; i < 7000000000; i++) {
//Do nothing, but wait ...
y = y+1;
}
console.log('F1 has finished');
return y;
}
//This is a Callback function usage //
function f2(x, myCallbackFunction) {
console.log('F2 is running ...');
let y = 0;
for(var i = 0; i < 5000000000; i++) {
//Do nothing, but wait ...
y = y+1;
}
console.log('x='+x);
console.log('F2 Before CallBack');
myCallbackFunction(x);
console.log('F2 has finished');
// A function can return or not a value //
return x;
}
//This is a Callback function usage //
function f3(x, myCallbackFunction) {
console.log('F3 is running ...');
let y = 0;
for(var i = 0; i < 1000000; i++) {
//Do nothing, but wait ...
y = y+1;
}
console.log('x='+x);
console.log('F3 Before CallBack');
myCallbackFunction(x);
console.log('F3 has finished');
}
// This is A SYNCHRONOUS code !! //
let x1 = f1();
console.log('Function 1='+x1);
let x2 = f2(21, myCallback);
f2(22, myCallback);
console.log('Function 2='+x2);
f3(3, myCallback);
And here it is the console log when I run the script: