DEV Community

Marouane Souda
Marouane Souda

Posted on • Updated on

Convert A Promise To ASYNC/AWAIT

Hello everyone!

This is my very first post, so I hope it'll be as helpful as I want it to be.

How to convert a promise-based asynchronous code to async/await format, thus making it more readable?

As we all know, Promises were an improvement over callbacks after they were included in JavaScript as part of the ECMAScript 6 specification. But they do tend to get messy in their own way. Maybe not as hellish as callbacks (callbacks pyramid of doom anyone?), but enough to warrant an upgrade to a more readable syntax.

And this is where async/await comes in.

Convert a simple Promise.

First, let's start with a simple Promise:

Alt Text

This is a simple function that returns a promise. The promise resolves to a value of type string, and of value "resolved" after 5000 milliseconds, or 5 seconds.

Alt Text

We are calling the function, and after returning the promise, the then method will be called after 5 seconds, and "resolved" gets logged to the console.

The whole code looks like this

Alt Text

What we want to do is turn it into an async/await code.

First, let's put the whole thing inside of a function. This is important, because await only works inside a function preceded by an async keyword. We will add it later.

Alt Text

Here we created a new function, inside of which the promise is stored in a variable v. If we try and log v to the console, we can see that it is a promise object.

The important thing we should note is that await is the main keyword here, async is just a wrapper, but without it, await won't work.

So we will add it

Alt Text

The function usually returns an undefined value if no return statement was specified. but with async, it returns a promise, but that's an entire point on its own, and beyond the scope of this post.

After adding the async keyword, nothing should really change. v is still a promise, but what if we add await before calling myPromise?

Alt Text

As we can see, if we wait 5 seconds, "resolved" is logged, and v is a string, not a promise object. So, await resolves the promise, and we get the value directly. And our code is much cleaner.

The true benefit of async/await manifests itself when you try to chain multiple then statements with each other, which looks clumsy. With await, it'll be way easier to read and debug.

I hope this post has helped you if you want to understand async/await to learn async/await. They are actually very easy once you know how to use them.

If you have any comments, notes, or constructive criticism, please add them below, and thanks for reading.


Connect with me on:

Top comments (0)