I've translated my old pure promises funcion to asyn wait function in a backend apollo server, consumed by a react app
All is working well, but i have a doubt about the behaviour magic in async/await function:
here my old code:
const signIn = (args) => {
return new Promise((resolve, reject) => {
return User.findOne({ where: {nick: args.nick }})
.then((user) => {
if (user == null) {
return reject({
code: 'error.loginNick',
message: 'Authentication failed. User not found.'
});
}
if (user.password != args.password) {
console.log('pass incorrect:' + args.password + ' = '+ user.password);
return reject({
code: 'error.loginPassword',
message: 'Wrong password.'
});
}
return resolve(createToken({ id: user.id, nick: user.nick }));
})
.catch(err => {
reject(err);
});
});
};
createToken function:
exports.createToken = payload => (
jwt.sign(payload, config.auth.secret, {
expiresIn: config.auth.expiresIn
})
);
In my singIn function i need to call this last function with:
resolve(createToken.....
if I don't use resolve, my app does not work well because wait a promise. No strange until here, but the behaviour is different in my new rewritten function signIn using async.
my full new async function:
async function signIn(args) {
try {
let err;
if (!args.nick) {
err = {
code: 'nick.empty',
message: 'Nick is empty.'
};
} else if (!args.password) {
err = {
code: 'password.empty',
message: 'You have to provide a password.'
};
}
if (err) {
throw (err);
}
// Find the user
const user = await User.findOne({
where: {
nick: args.nick
}
});
if (user == null) {
err = {
code: 'error.loginNick',
message: 'Authentication failed. User not found.'
};
throw (err);
}
if (user.password != args.password) {
console.log('pass incorrect:' + args.password + ' = ' + user.password);
err = {
code: 'error.loginPassword',
message: 'Wrong password.'
};
throw (err);
}
//return Promise.resolve(createToken({ id: user.id, nick: user.nick })); <-- workin ok too
return createToken({
id: user.id,
nick: user.nick
});
} catch (err) {
throw (err);
}
}
export {
Customer,
Tour,
User,
Auth,
signIn
};
If i use these two alternatives, boths works well ! why ? ok with Promise I understand well that it's works, but wihtout promises is working ok too, not same behavoiur like my old promises function
alternative 1 without promise:
return createToken({ id: user.id, nick: user.nick });
why don't need here promises?, the twhrow if there error go where?
alternative 2 with promise:
return Promise.resolve(createToken({ id: user.id, nick: user.nick }));
the twhrow if there error go where? this last alternative is anti Pattern ?