UNPKG

nodejslearnerfiles

Version:

Very Good Beginnings if you want to Learn Node.js

46 lines (36 loc) 1.27 kB
var maxTime = 1000; // if input is even, double it // if input is odd, return error. // ( call takes random amount of time < 1 sec ) var evenDoubler = function(v, callback) { var waitTime = Math.floor(Math.random()*(maxTime+1)); if(v%2) { setTimeout(function (){ callback(new Error("Odd Input"), null, waitTime); }, waitTime); } else { // Multiple parameters in a successful callback. setTimeout(function (){ callback(null, v*2, waitTime); }, waitTime); } }; // handleResults is a named function. // a callback function usually have errors in the beginning and results and other additional parameters at the end of the argument list. var handleResults = function(err, results, time) { if (err) { console.log("ERROR: "+ err.message +" ("+ time + "ms)" ); } else { console.log("The results are : "+ results + " ("+ time + "ms)"); } }; // Calling the Asynchrnous function with callbacks, which means, once it is ready with "evenDoubling", it will invoke the "callback" function. evenDoubler(2,handleResults); evenDoubler(3,handleResults); console.log("............"); /*output Debugger listening on [::]:15454 ............ The results are : 4 (170ms) ERROR: Odd Input (866ms) */