“Await”! You don’t need my Promises!
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.

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).

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.

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


