How to make callback function in async/await style?

Viewed 4035

Currently I'm working with jwt in node.js app. I use jwt.sign() method which looks like this:

jwt.sign({
            accountID: user.accountID,
            email: user.email,

        }, process.env.SECRET_KEY, (err, token) => {

            if (err) throw err
            res.json({token})
        })

I don't want to use callback. I want to transform this to async/await. As I know I have to return new Promise with resole({}) and reject(err). But I can't figure out how to use promise from sign() method. Any help appreciated. Thanks!

2 Answers

JavaScript (as well as libraries like Bluebird) has a built-in promisify function as util.promisify(), which will take functions with standard callback format like this and turn them into async promises. However, you can take the behind-the-scenes work and run it yourself, by wrapping the function you're trying to promisify in a new Promise call. Failing the utility, I'd do something like:

function sign(id, email, secret) {
  return new Promise((resolve, reject) => {
    jwt.sign({ accountID: id, email: email }, secret, (error, token) => {
      if (error) {
        reject(error);
      } else {
        resolve(token);
      }
    });
  });
}

You can then call it as:

const token = await sign(user.accountID, user.email, process.env.SECRET_KEY);
Related