Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda