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!
- 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
2 Answers
Reset to default 9JavaScript (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