Node JS - Callback pattern


Callback is a function, that gets associated with another function. And this will get triggered back, once the another function done its operation.

Generally in Node JS it is being used to perform the synchronous operation. But callbacks pattern can also be associated with the synchronous function.


//A synchronous function
function printNum(num) {
  return num;
}
let number = printNum(3);
console.log("Start");
console.log(number);
console.log("End");



//A synchronous function, with callback
function printText(textcallback) {
  callback(text);
}

console.log("Start");
printText("Avinash", (returnText=> {
  console.log(returnText);
});
console.log("End");




//An Asynchronous function : Callback using process nextTick
function printSum(numcallback) {
  //Introduce async behaviour to response data in the next tick of event loop
  process.nextTick(() => {
    callback(num + 5);
  });
}

console.log("Start");
printSum(5, (returnValue=> {
  console.log(returnValue);
});
console.log("End");





//An Asynchronous function : Callback using setTimeout

function printMul(numcallback) {
  setTimeout(() => {
    callback(num * 3);
  }, 3000);
}

console.log("Start");
printMul(3, (responseVal=> {
  console.log(responseVal);
  printMul(2, (val=> {
    console.log(val);
    printMul(1, (val=> {
      console.log(val);
    });
  });
});
console.log("End");