Async/Await Function is Officially Shipped in NodeJS v7.6.0

With the release of NodeJS v7.6.0, Async/Await function is now native and you don’t need to apply harmony flags to run the code with Async/Await function.

NodeJS v7.6.0 contains V8 5.5, in this blog post, V8 team confirms to introduce ES2017 function called Async/Await.

What is Async/Await function

Async functions allow you to write promise based code as if they are synchronous, without blocking the event loop ( Very important!)

For example, consider this promise based code.

JAVASCRIPT
function logFetch(url) {
  return fetch(url)
    .then(response => response.text())
    .then(text => {
      console.log(text);
    }).catch(err => {
      console.error('fetch failed', err);
    });
}

Do not consider it as a working code, it’s for demonstration purpose. So here, we are trying to fetch the URL and we are using promise to handle the flow.

Here is how we can write the same code using Async function.

JAVASCRIPT
async function logFetch(url) {
  try {
    const response = await fetch(url);
    console.log(await response.text());
  } catch (err) {
    console.log('fetch failed', err);
  }
}

To make the function Async, we append the async keyword before a function definition, then you can use await within the function.

When you await a result in form of promise, the function is paused in a non-blocking way until the promise settles.

If the promise fulfills, you get the value back. If the promise rejects, the rejected value is thrown.

And all of this happens without blocking the event loop.

How to update to NodeJS v7.6.0

To update to this Nodejs version or any version for that matter, I recommend using node version manager called N. You can refer this tutorial to learn more about it.

Once you have the node version manager, run this command to get the latest Nodejs version.

COMMAND
n stable

Nodejs Async Await

Other than Async/Await, there is an improvement of memory consumption and introduction to more API’s. You can find complete reference of the release here.

If you are new to Node.js and would like to learn practically, I recommend you this course. It’s worth every penny!

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126