Typescript async/await not working Typescript async/await not working typescript typescript

Typescript async/await not working


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


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 laterconst 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.