Member-only story
JavaScript Async Await: Promisify the future to callback never again!
Callbacks to Promises up to Async Await
Intro
Having a C# background? Then you are familiar with async-await. JavaScript introduced these keywords in 2017 into the language. They help to get rid of problems you had back then whenever it came to asynchronous code.
Asynchronous code, known for using callbacks so far, that are mostly nested and lead to hardly comprehensible code. Here is a picture of a callback hell or also known as the pyramid of doom [2], [1].
There are plenty of options to solve this problem, but none of them came out big and became the method to go along. All of them bring their own problems to the table. Be it promises or generator functions or even modules like Async.JS [3].
Yesterday’s code
Although async and await is a significant change, we should not throw away old concepts. Async await is based internally on generator functions and promises. And on what do promises rely on? Right! Callbacks. New abstraction levels bring better ways to encapsulate old concepts but also keep the same problems. Joel on Software did a great job about that circumstance [4].
Concrete speaking: Async-Await is only usable with functions that already rely on promises. If you have methods that aren’t, you have to convert them in order to use async-await. A good way to do so is to use a technique so-called wrapping. Wrap your existent callback-based function into another function that uses a promise. Here is an example of the usage of a readFile to show you what I mean.
The wrapper function is clearly visible, calling the promise constructor. The body exposes the origin function, based on the callback mechanism.