async / await wrapper for callback style javascript code

Sudhakar Rayavaram
Dec 4, 2018 · 1 min read

I love javascript async/await. They make the asynchronous code clean to write and easy to read in synchronous style

But, there are many libraries created out there which were before async/await and when we end up using these libraries, our code is back to callback hell. Instead of looking around for a library that supports async/await, there is a better way

Wrap all the callback code inside an async function in a separate file and call the wrapper with await

example function from a library

Let us take an example of a function written in callback style. awesomeFunction takes in an input and a callback. At some later point in time, it invokes the callback function with result and error

using awesomeFunction involves passing a callback function which gets results and error objects

To write the above code in async / await style, let us create an async wrapper function as shown below

awesomeFunctionWrapper is creating a new Promise and awaiting on this promise object. The promise resolve and reject functions are triggered based on the callback function results

Now we can await on the awesomeFunctionWrapper to write a code that looks cleaner

Tarka Labs Blog

Tarka Labs is a team of passionate hackers, designers and product managers. We believe in experimental methods to identify the best solutions to problems instead of working on technology du jour. Visit us at https://tarkalabs.com/

Sudhakar Rayavaram

Written by

Software plumber, health and wellness enthusiast, digital artist, data visualization lover & …

Tarka Labs Blog

Tarka Labs is a team of passionate hackers, designers and product managers. We believe in experimental methods to identify the best solutions to problems instead of working on technology du jour. Visit us at https://tarkalabs.com/

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade