0

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 ?

zero_cool
  • 3,960
  • 5
  • 39
  • 54
DDave
  • 1,400
  • 3
  • 16
  • 33
  • 1
    `why don't need here promises` - **async** functions always return a Promise – Jaromanda X Oct 23 '17 at 03:12
  • `return resolve(createToken` ... no, it's in a .then, so no need to create a Promise, .then does it for you - in fact, since `return User.findOne` returns a Promise, there's no need for [a promise constructor anti-pattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – Jaromanda X Oct 23 '17 at 03:12
  • so, your Promise code, could be written https://jsfiddle.net/yebmthxc/ - your async/await code would be https://jsfiddle.net/01x2o4ft/ – Jaromanda X Oct 23 '17 at 03:17
  • thanks, it does mean that if async return always a promise, wrapper insider promise don't throw errors? what about if findOne, throw erros? where catch them? – DDave Oct 23 '17 at 07:59
  • wherever you call `signIn` - just like in your Promise version, because you are effectively not handling errors in your code (which is probably correct, without knowing how you are calling `signIn` I can only speculate - I'm 99% confident that both versions of code I've suggested are functionally equivalent to each other, and your intent with the Promise code – Jaromanda X Oct 23 '17 at 08:08

0 Answers0