Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
NodeJS responds before function is done

I'm writing an API with NodeJS and Express for a schoolproject and I'm struggling with the following:

The function getAuthUserId decodes the JWT token and gets the Id from user in the mongoDB server.

I call this function in a REST call "/user/authTest". But when I call this, the server responds before the database can return the Id, and the variable UId is undefined. As you can see, the Id is actually found. Any ideas on how i can fix this?

The API call code:

apiRoutes.post('/user/authTestID', function(req, res) {
  var UId = getAuthUserId(req, res);
  console.log(UId);
  if (UId) {
    res.sendStatus(200);
  }else{
    res.sendStatus(400);
  }

}); 

The function:

function getAuthUserId(req, res) {
    var user = new User();
  var token = user.getToken(req.headers);
  if (token) {
    var decoded = jwt.decode(token, config.secret);
    User.findOne({
      name: decoded.name
    }, function(err, user) {
        if (err) throw err;

        if (!user) {
          res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
          return false
        } else {
          console.log('Auth for ' + user.name + ' ' + user._id);
          return user._id
        }
    });
  } else {
    res.status(403).send({success: false, msg: 'No token provided.'});
    return '';
  }
}

The output of the terminal:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Connected to MongoDB
undefined
::ffff:192.168.0.111 - POST /user/authTestID HTTP/1.1 400 11 - 175.006 ms
Auth for test 58f8954c3602b80552b6f1fb

Thanks in advance!

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You need to make it a promise, like this.

API

apiRoutes.post('/user/authTestID', function(req, res) {
  getAuthUserId(req, res).then(function (UId) => {
    console.log(UId);

    if (UId) {
      res.sendStatus(200);
    }else{
      res.sendStatus(400);
    }
  });

}, function(err) {
    console.log(err.msg)
    res.status(err.status).send(err.msg);
});

Function

function getAuthUserId(req, res) {
    return new Promise(function(resolve, reject){
        var user = new User();
        var token = user.getToken(req.headers);
        if (token) {
            var decoded = jwt.decode(token, config.secret);
            User.findOne({
                name: decoded.name
            }, function(err, user) {
                if (err) throw err;

                if (!user) {
                    reject({status: 403, msg: 'Authentication failed. User not found.'});
                } else {
                    console.log('Auth for ' + user.name + ' ' + user._id);
                    resolve(user._id)
                }
            });
        } else {
            reject({status: 403, msg: 'No token provided.'});
        }
    })
}
about 4 years ago · Santiago Trujillo Denunciar

0

getAuthUserId get's the value in a CALLBACK !!! . You can't expect it to return values from it. As quick thing you can do something as below.

        apiRoutes.post('/user/authTestID', function (req, res) {
            var user = new User();
            var token = user.getToken(req.headers);
            if (token) {
                var decoded = jwt.decode(token, config.secret);
                User.findOne({
                    name: decoded.name
                }, function (err, user) {
                    if (err) throw err;
                    if (!user) {
                        return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
                    } else {
                        console.log('Auth for ' + user.name + ' ' + user._id);
                        return res.send(user._id)
                    }
                });
            } else {
                return res.status(403).send({success: false, msg: 'No token provided.'});
                // return '';
            }
        });

Try using Promise library like Bluebird

about 4 years ago · Santiago Trujillo Denunciar

0

James' comment looks like a good, thorough resource on async calls. As others have mentioned, you cannot return values within a callback. You can use a Promise library, or you can change your getAuthUserId function to take a callback and have your console.log logic in there:

Example:

API call code:

apiRoutes.post('/user/authTestID', function(req, res) {
  getAuthUserId(req, res, function(UId) {
  // we're in a your new callback
  console.log(UId);
  if (UId) {
    res.sendStatus(200);
  }else{
    res.sendStatus(400);
  }
  });
});

Function Code

// note new callback param
function getAuthUserId(req, res, callback) {
  var user = new User();
  var token = user.getToken(req.headers);
  if (token) {
    var decoded = jwt.decode(token, config.secret);
    User.findOne({
      name: decoded.name
    }, function(err, user) {
        if (err) throw err;

        if (!user) {
          res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
          callback(false) // no more return, call callback with value
        } else {
          console.log('Auth for ' + user.name + ' ' + user._id);
          callback(user._id) // no more return, call callback with value
        }
    });
  } else {
    res.status(403).send({success: false, msg: 'No token provided.'});
    callback(''); // no more return, call callback with value
  }
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda