简体   繁体   English

如何使异步/等待风格的回调函数?

[英]How to make callback function in async/await style?

Currently I'm working with jwt in node.js app. 目前,我正在node.js应用程序中使用jwt I use jwt.sign() method which looks like this: 我使用jwt.sign()方法,如下所示:

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 . 我想将其转换为async/await As I know I have to return new Promise with resole({}) and reject(err) . 据我所知,我必须返回带有resole({})reject(err) new Promise But I can't figure out how to use promise from sign() method. 但是我不知道如何使用sign()方法中的promise。 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. JavaScript(以及诸如Bluebird之类的库)具有一个内置的promisify函数,如util.promisify() ,它将采用标准回调格式的函数,并将其转化为异步承诺。 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. 但是,您可以通过在新的Promise调用中包装您要推广的功能,来进行幕后工作并自己运行。 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. 如果在node.js 8中使用上述代码,则可以使用promisify方法。 Check the proposal here: http://2ality.com/2017/05/util-promisify.html 在此处检查建议: http : //2ality.com/2017/05/util-promisify.html

For other implementations consider using Bluebird promise library or any similar library. 对于其他实现,请考虑使用Bluebird Promise库或任何类似的库。 Bluebird promisify reference: http://bluebirdjs.com/docs/api/promise.promisify.html Bluebird承诺参考: http ://bluebirdjs.com/docs/api/promise.promisify.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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