最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make callback function in asyncawait style? - Stack Overflow

programmeradmin0浏览0评论

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!

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!

Share Improve this question asked Oct 29, 2018 at 18:18 NastroNastro 1,7698 gold badges24 silver badges42 bronze badges 2
  • just wrap it all in a function and prepend "return await " to the code shown – dandavis Commented Oct 29, 2018 at 18:21
  • 4 require('util').promisify(jwt.sign) should work. – Patrick Roberts Commented Oct 29, 2018 at 18:24
Add a ment  | 

2 Answers 2

Reset to default 9

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./2017/05/util-promisify.html

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

发布评论

评论列表(0)

  1. 暂无评论