0

I have some code which creates a web token and send it back to the user. So the code starts first by calling the createToken function. This function asyncrnous, when the webtoken is done creating it will then return. The problem is inside of my main code I send back a request back to the user with the token, the problem is this send back response gets sent before the token is created. I understand why this happening as this is an async function and it will return the token when it is ready, meanwhile the code will continue to go on hence the response back to the client is sending a response back where the token variable in undefined. My question is how do I fix this? One way I know will work is if I put the response inside of the creaeToken function, but I don't want to do this as the createToken function is used throughout my application for various other reasons and sometimes those reasons don't include a response back to the client at all. So my question is how can I send the response back to the client only when the token has been created?

var token = tokensUtil.createToken(username);
res.send('{"token":"' + token + '"}');

The createToken method looks like this:

var createToken = function(username){

var token = jwt.sign({ "username": username}, secret, {expiresIn: "2h", issuer: issuerName}, function(token){
        console.log(token);
        return token;
    }); 
};
user2924127
  • 6,034
  • 16
  • 78
  • 136

0 Answers0