简体   繁体   中英

How to make callback function in async/await style?

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!

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);

If you are using the above code in node.js 8,you can use the promisify method. Check the proposal here: http://2ality.com/2017/05/util-promisify.html

For other implementations consider using Bluebird promise library or any similar library. Bluebird promisify reference: http://bluebirdjs.com/docs/api/promise.promisify.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM