Convert a Promise to an async function

Viewed 111

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.

2 Answers

You are getting a function instead of a Promise because new Promise creates a promise immediately, but async () => {} only creates a promise when it is called.

… but that is the least of your problems.

async functions are tools to manage existing promises. They are not freely interchangeable with the promise constructor.

passport.authenticate doesn’t return a promise, so you can’t use async to manage it.

As mentioned above, you can not use it like this here. However, in case you would need to write an async function, it would look like this.

export const getUser = async (req: Express.Request, res: Express.Response) => {
   return await functionThatReturnsAPromise()
}
Related