I'm pretty new to javascript and am trying to convert the code below to an async function. As I understand it an async function always returns a Promise.
// working code
export const getUser = (req: Express.Request, res: Express.Response) =>
new Promise((resolve, reject) => {
passport.authenticate('oauth-bearer', { session: false }, (err, user) => {
if (err) reject(err)
if (user) resolve(user)
else reject('Unauthorized')
})(req, res)
})
This Promise is being used with the await
keyword:
const user = await getUser(req, res)
My attempts thus far always return a "Function" and not a resolved or rejected Promise:
// failing code
export const getUser = (req: Express.Request, res: Express.Response) =>
async () => {
return await passport.authenticate('oauth-bearer', { session: false }, (err, user) => {
if (err) throw err
if (user) return user
else throw 'Unauthorized'
})(req, res)
}
Thank you for pointing out what I'm doing wrong here.
passport.authenticate
doesn't return a Promise, then you can't.async
functions are syntactic sugar around promises; if there is no promise, you can't use that syntax. – deceze♦ Aug 20 '20 at 7:33passport.authenticate
is indeed a normal function. But it calls a callback. And I was hopen it was possible to wrap that in anasync
function. So I don't have to use thenew Promise
syntax. – DarkLite1 Aug 20 '20 at 7:37