I have some questions about best practices to apply in JavaScript. I would like to ask about my code and how I could improve.

Starting with an example, I have 2 functions with different ways of handling promises

Here I have a route to add a user:

 addUsers(req,res,next) {
try {
.then(async result => {
if(!result){
User.create({
res.status(201).json({Results: result.dataValues})
})
}else{
}
})
} catch (error) {
res.status(500).json({error: error})
}
}


And here I have another function to login:

async login(req,res){
if (!user) { return res.status(400).json({result: 'Login is wrong '});}
console.log(jwt);
res.status(200);
res.json(jwt);
}


Looking at this the login function seems to me to be cleaner, but I have doubts if really yours I could improve in one of two (I follow different logics to do both).

I have an auth folder, where I export functions, such as my payload, my sign, my middleware to validate my jwt, but I don't know if this is a correct decision.

const jwt = require('jsonwebtoken');
const User = require('../models/User')
const config= require('../config/dbconfig');
const moment = require('moment');

module.exports = {
config.secretToken
)
},
return {
sub: usuario.id,
name: usuario.nome,
email: usuario.email,
iat: Math.floor(moment.now()/1000), // Timestamp de hoje
}
},
async auth(req,res,next){
console.log(token);
if(!token) return res.status(401).json('Unauthorized');
try{
const decoded = jwt.verify(token,config.secretToken);
const user = await User.findByPk(decoded.sub);
console.log(user);
if(!user){
}
res.json(user);
next();
}catch(error){
console.error(error);
res.status(400).json('Invalid Token');
}
}
}

• "with different ways of handling promises" - avoid mixing await and .then(…) syntax, yes. Don't pass async functions as callbacks. Btw, one mistake that probably stems from this confusion is that you're not handling rejections from User.existLogin. – Bergi Nov 19 '19 at 0:06