anderish
anderish

Reputation: 1759

Callback Not Working in NodeJs

I am trying to handle asynchronous calls in NodeJs. Here is my code:

function getUserFromToken(token) {
  decodeJWT(token, function (err, data) {
    console.log("Call back Worked");
  })
}

function getUserProfile(user_id, username, hashPass, callback) {
  let sql = "SELECT first_name, last_name, username FROM User where user_id=? AND username=? AND password=?";

  db.query(sql, [user_id, username, hashPass], function (err, result) {
    if (err) callback(err, null);
    else callback(null, result)
  });
}

function decodeJWT(token, cb) {
  jwt.verify(token, config.secret, function (err, decoded) {

    if (err) res.status(401).send({auth: false, message: miscConstants.INVALID_TOKEN});

    const {user_id} = decoded;
    const {username} = decoded;
    const {hashPass} = decoded;

    getUserProfile(user_id, username, hashPass, res, function (err, profile) {

      cb(null,'yo');
    });

  });
}

The callback used in the getUserProfile function works but, it never reaches the console.log("Call back Worked");. Any ideas?

Upvotes: 1

Views: 64

Answers (1)

TMarafon
TMarafon

Reputation: 337

The callback is not being called because your call to getUserProfile is passing 5 parameters user_id, username, hashPass, res, function, while the function is expecting only 4:

getUserProfile(user_id, username, hashPass, res, function (err, profile) {...}

And the function:

function getUserProfile(user_id, username, hashPass, callback)

To make it work, just delete the parameter res in the getUserProfile call.

Upvotes: 1

Related Questions