Lets do a quick one today that can make your JavaScript code much cleaner and much much more readable, namely JavaScript Async / Await.
What is Async / Await?
Async / Await is a way to write asynchronous code as if it were synchronous.
This is a big deal because you’re probably writing tonnes of asynchronous code and a majority of it is probably just fetching some data, this quickly becomes a pain in the ass because every time you do this you need to write 5 goddamn lines of code for a simple assignment operation.
F that noise!
Lets look at an example
const initAsyncData = async () => {
const data1 = await somethingAsync();
const data2 = await somethingAsync();
const data3 = await somethingAsync();
return 'finished';
};
function somethingAsync() {
return new Promise((resolve, reject) => {
resolve({ ok: true });
});
}
initAsyncData();
The code above waits until the first ‘somethingAsync()’ is done then waits for the second one then waits for the third one and finally wraps things up by returning ‘finished’.
Couple of important things to note:
- ‘await’ can only be used inside ‘async’ functions
- ‘async’ functions return a promise implicitly
- Resolve value of the ‘async’ function is whatever we return from it. In our case we resolve ( return ) ‘finished’
When can I use this sweet sweet new tech?!
How about right now, PLAYA!
Async / Await is a really popular feature that got a lot of people talking so it should come as no surprise that the support is pretty good!
caniuse (Link) shows that major browser vendors are serious when it comes to Async / Await.
node support table (Link) paints a similar picture as caniuse. Newer node versions fully support Async / Await!
If the above isn’t good enough for you you can always use something like Babel (Link) to make sure your Async / Await code runs everywhere.
If you use TypeScript ( Angular 2+ developers I’m looking at you ) you’ll be happy to learn that it’s been supported for a while now (Link)
Slow the hype train down
Async / Await is awesome. Agreed. But don’t get too sucked in to the hype and try to force Async / Await on every
single asynchronous call like I’ve seen some developers try to do.
I don’t consider Async / Await a replacement for Promise.then
but a new tool to use alongside it, always use
the tool that makes the most sense, is clean and readable.
Be smart.