Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Callback in node.js

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 570
    Comment on it

    A callback is a function which is highly used in node js. When we want to run any task after the success or completion of a given task then we will use a callback. We will write maximum API in such a way that they will support callback.

    I will explain this by using a callback function example:

     

    Example:

    var express = require('express');
    var app = express();
    var forloop = require('forloop');
    
    
    var sumCallback = function(req, res) {
    	var num = req.params.num;
    	if (isNaN(num) || num < 0) {
    		res.status(500).send({ error: "Not a valid number" });
    	} else {
    		sum(num, function(k) {
    		 responseSuccess(num, k, function(response){
    			 //console.log(num);
           //console.log(parseInt(num));
    			 //response = parseInt(num) + parseInt(num);
    			 res.send(response);//.toString());
    		 })
    	  })
    	}
    
    };
    
    app.get('/sum/:num', sumCallback);
    
    
    app.listen(3000, function() {
    	console.log('App listening on port 3000!');
    });
    
    var sum = function(num, callback) {
    	var k = 0;
    	num = parseInt(num) + 1;
    	//logger.debug("Start Here...");
    	forloop(0,num, 1, function(n) {
    		k = k + n;
    	}, function() {
    		//logger.debug("End Here...");
    		callback(k);
    	});
    }
    
    var responseSuccess =  function(num, k, cb) {
    	var resString = "The sum of numbers from "+ num +" to  is: " + k;
    	cb(resString);
    }

     

    Let see how the callback is working in the above example. First when we write localhost:3000/sum/23 on the browser then first it will call to the app.get('/sum/:num', sumCallback); routes. Then it will go to the sum function there we pass callback then we check number exists or not  if the number exists then on the success of the function we will move further else we will display error. In else case we will call one more function sum there we also write one more callback. If sum function will return any result then inside sum callback will occur and display the result.

    So here we see that callback is used in every phrase in node.js. We will use most to the function using a callback in node.js.

     

    Note: So it clear when we want our code run on the success of the function then we will pass  callback in our function.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: