Mahesh G
Mahesh G

Reputation: 1276

Understanding Callback function in NodeJS

I am very new to Node Js and Concept of Callback Mechanism , I have working code to authenticate the User based on the LDAP using ldapjs but I wanted to know the mechanism how its working with respect to data flow and callbacks.

In the below code I have few doubts, Can someone help me clarifying

  1. What does it means with cb(err === null, err, res);
  2. When I do console.log with fake_res it shows as true Why its true?
  3. I see some post referring we need use to error as first callback, Is it so?
  4. And Finally I wanted to understand why is the res used in output and authDN are same
  5. And finally how generally callbacks works in NodeJS

Before asking this question I have gone through many forums but couldn't relate with the below code

  1. Link 1
  2. Link 2
  3. Link 3
  4. Link 4

var express = require('express');
var util = require('util');
CircularJSON = require('circular-json');
var router = express.Router();
var ldap = require('ldapjs');
var bodyParser = require('body-parser');
var userNT;
var password;


var app = express();

function authDN(dn, password, cb, res) {
  var client = ldap.createClient({
    url: 'ldap://localhost:389'
  });
  client.bind(dn, password, function(err) {
    client.unbind();
    cb(err === null, err, res);
  });

}

function output(fake_res, err, res) {
  if (fake_res) {
    console.log('success');
    res.status(200).send('{"status":"success"}');

  } else {
    console.log('failure');
    res.status(401).send('{"status":"failure"}');
  }

}

app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({
  extended: true
})); // support encoded bodies

router.post('/login', postData);

function postData(req, res) {
  userNT = req.body.ntid;
  password = req.body.password;
  authDN(userNT, password, output, res);
};


module.exports = router;

Upvotes: 0

Views: 1072

Answers (1)

TGW
TGW

Reputation: 835

Okay let us go try to do it step by step :

Here if you see authDN has third parameter cb this is your callback function. Now to trace it back check the value of argument provided to this function authDN when it is called inside postData function, here cb = function output

Now first param of your output is fake_res which is either true or false, this depends on response of client.bind

If it fails you will get some error hence it will go on to be false. Here comes the answer to your question 2 because your credentials seem to be correct always this err is equal to null thus your fake_res is always true.

Answering question 4 it is because it is passed on as param to send response back to the API call you made using router.post

About number 3 it is just more readable and better to use an error first callback, but not necessary.

Upvotes: 1

Related Questions