callback function nodejs code example

Example 1: node js callback

function processData (callback) {
  fetchData(function (err, data) {
    if (err) {
      console.log("An error has occurred. Abort everything!");
      return callback(err);
    }
    data += 1;
    callback(null, data);
  });
}

processData(function (err, data) {
  if (err) {
      console.err(err);
  } else {
    console.log("Data: " + data);
  }
});

Example 2: callback in response node.js

//you can only return a value from an async function by passing in a callback function like so: 
function longRunningFunction(param1, callback){
    setTimeout(function(){
         var results="O High there!";
         callback(results);
    }, 2000);
} 

//then call the async function and pass the callback function like so
longRunningFunction("morning", function(result){
  alert(result);
});