Handle callback style function with async/await in javascript

Mitsuhide Ohi
1 min readDec 25, 2020

--

Sometimes you need to work with a callback style function from 3rd party library or an existing one in your codebase. Something like this.

const generateToken = (callback) => {
...
// some async process ... callback(token) // success case ... callback(null, error) // failure case}

You will have a problem if you want to use it in the async function. You could turn the function into also async function, not taking the callback function but most of the time you have no control or you don’t want to touch it. This is an easy solution for this kind of situation and I will describe it as much as short and simple.

You can create a wrapper function that calls the original function inside and returns a Promise.

const generateTokenWrapper = () =>
new Promise((resolve, reject) => {
generateToken((token, error) => {
if (error) {
reject(error)
} else {
resolve(token)
}
})
})

And you can use it like this in your async function.

try {
const token = await generateTokenWrapper()
console.log({ token })
} catch (error) {
console.error({ error })
}

That’s it. I hope it works in your situation.

Lastly, here’s a working example. Enjoy!

--

--

No responses yet