JavaScript Async / Await
Published: 08 Nov 2017
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
1const initAsyncData = async () => {2 const data1 = await somethingAsync();3 const data2 = await somethingAsync();4 const data3 = await somethingAsync();5 return 'finished';6};78function somethingAsync() {9 return new Promise((resolve, reject) => {10 resolve({ ok: true });11 });12}1314initAsyncData();15
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:
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
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.
Share Article on: or