“Await”! You don’t need my Promises!

ANTHONY
ANTHONY
Sep 6, 2018 · 3 min read

Refactoring common Promises with Async/Await in Javascript.

As a developer, I can’t accept too easily poor code design. There’s always a little voice telling me “something can be improved”.

For instance, look at the following code I wrote. The code executes and works correctly, however, there’s still space for improvement.

Using a Promise to return the result of a callback call

As you can see, I’m using a “Promise” to resolve the response value from asynchronously calling the “getFuelLevel” method.

Can you spot the smelling part?

It’s the promise. I don’t find the code readable enough by wrapping my implementation within a Promise each time I need to resolve a value from a callback call.

It’s 2018 and the @JavaScript people know how to rock!

It can be of help having a more “synchronous” implementation. So I got rid of the Promise.

See the following screenshot: (I’m highlighting the important parts).

Implementation without using a Promise

As you can see in the previous image, I’m no longer wrapping my implementation within a Promise!

Instead, I’m making use of the async/await syntax.

How does that work? It’s simple, any async function returns a Promise! Yes, a Promise!

So it’s not necessary to return a “New Promise”!

Also, notice that “await” is making sure that the asynchronous code from calling getFuelLevel is resolved before returning the “_level” value at line 172.

Calling the carFuelLevel function

But wait, you’re returning a String and not a Promise from the “carFuelLevel” function! (see the previous screenshot)

If you look at the implementation, calling the carFuelLevel function expects a “Promise”, how then is a Promise returned and not a String value?

Well, it’s simple, any Async function will return a Promise and will wrap the returned value within the “Promise.resolve()” function.

Magic! So You see, there’s always space for improving your code!

I hope you have enjoyed this mini-series on #javascript #promises #async #await. What do you think? Anything I should learn from you? Leave your comments!

Follow me on twitter: https://twitter.com/anthonyrod4

If you enjoyed this story, please click the 👏 button and share to help others find it! Feel free to leave a comment below.

ANTHONY

Written by

ANTHONY

Software Architecture enthusiast | New York City

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