Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript async/await not working

I've a problem about async/await on typescript with target es2017. Below is my code :

my route.ts :

method: 'POST',
        config: {            
            auth: {
                strategy: 'token',        
            }
        },
        path: '/users',
        handler: (request, reply) {

    let { username, password } = request.payload;

    const getOperation = User
    .findAll({
        where: {
            username: username
        }
    })
    .then(([User]) => {
        if(!User) {
            reply({
                error: true,
                errMessage: 'The specified user was not found'
            });
            return;
        }

        let comparedPassword = compareHashPassword(User.password, password);
        console.log(comparedPassword);

        if(comparedPassword) {
            const token = jwt.sign({
                username,
                scope: User.id

            }, 'iJiYpmaVwXMp8PpzPkWqc9ShQ5UhyEfy', {
                algorithm: 'HS256',
                expiresIn: '1h'
            });

            reply({
                token,
                scope: User.id
            });
        } else {
            reply('incorrect password');
        }
    } )
    .catch(error => { reply('server-side error') });

};

my helper.ts :

export async function compareHashPassword(pw:string, originalPw:string) {
    console.log(pw);
    console.log(originalPw);
    let compared = bcrypt.compare(originalPw, pw, function(err, isMatch) {
        if(err) {
                return console.error(err);
        }
        console.log(isMatch);
        return isMatch;
        });

    return await compared;
}

this auth route supposed to return JWT token when user login. but the problem here is even when I enter the valid password to sign-in the function compareHashPassword always return undefined.

For example when i call the api with json string

{
  "username": "x",
  "password": "helloword"
}

When i track using console.log(), the log is :

$2a$10$Y9wkjblablabla -> hashed password stored in db
helloword 
Promise {
  <pending>,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function: bound ] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }
true

maybe this is just my lack of understanding about using async/await with typescript. for note my env is :

node : v8.6.0
typescript : v2.5.2
ts-node : v3.3.0
my tsconfig.json //
{
    "compilerOptions": {
        "outDir": "dist",
        "target": "es2017",
        "module": "commonjs",
        "removeComments": true,
        "types": [
            "node"
        ],
        "allowJs": true,
        "moduleResolution": "classic"
    },
    "exclude": [
        "node_modules"
    ]
}
like image 471
kola Avatar asked Sep 27 '17 09:09

kola


Video Answer


2 Answers

In order for async/await to work, an async function has to return a Promise. Also, you must call an async with the await keyword this way:

You can only call await inside an async function, so I wrapped it in an async func

const someFunc = async function() {
    return new Promise((resolve, reject) => { 
        setTimeout(resolve, 100, true);
    });
};

(async () => {
     const result = await someFunc(); // true
})();

You are not satisfying any of these rules in your compareHashPassword declaration and the way you call it.

This is how I would rewrite your code :

export async function compareHashPassword(pw:string, originalPw:string) {
    return new Promise((resolve, reject) => {
        bcrypt.compare(originalPw, pw, function(err, isMatch) {
            if(err) {
                reject(err);
            }
            console.log(isMatch);
            resolve(isMatch);
        });
    });
}

// and call it this way
(async () => {
     const compared = await compareHashPassword(pw, originPw);
})()

Have a look at this async await blog post: https://ponyfoo.com/articles/understanding-javascript-async-await

And this blog post for Promises: https://developers.google.com/web/fundamentals/primers/promises

Also as @Patrick Roberts mentioned, you can use util.promisify to turn an async callback style function into a Promise, this is node 8.xx otherwise you can use bluebird package which has a similar functionality.

Hope this helps

like image 182
Francois Avatar answered Oct 17 '22 19:10

Francois


Since you're targeting ES2017, let's clean up your code, starting with the simpler helper.ts:

import { promisify } from 'util' // you'll thank me later

const compare = promisify(bcrypt.compare)

export async function compareHashPassword(pw:string, originalPw:string) {
    console.log(pw);
    console.log(originalPw);
    return compare(originalPw, pw);
}

Now for the route.ts:

handler: async (request, reply) => {
  let { username, password } = request.payload;

  try {
    const [user] = await User.findAll({
      where: {
        username: username
      }
    })

    if(!user) {
      reply({
        error: true,
        errMessage: 'The specified user was not found'
      });

      return;
    }

    let match = await compareHashPassword(user.password, password);

    console.log(match);

    if (match) {
      const token = jwt.sign({
        username,
        scope: User.id
      }, 'iJiYpmaVwXMp8PpzPkWqc9ShQ5UhyEfy', {
        algorithm: 'HS256',
        expiresIn: '1h'
      });

      reply({
        token,
        scope: user.id
      });
    } else {
      reply('incorrect password');
    }
  } catch (error) {
    reply('server-side error')
  }
}

Hopefully I've matched what you're attempting to accomplish, based on the code you've provided. If there's an issue somewhere with this updated code, please let me know in the comments.

like image 26
Patrick Roberts Avatar answered Oct 17 '22 20:10

Patrick Roberts