1
Write a post

ES7 Async/Await Functions

Published Aug 09, 2017Last updated Aug 11, 2017
ES7 Async/Await Functions

Javascript seems to be growing at the speed of light, well compared to other languages out there that I know of. As it grows, it’s been adding new features to it’s newer versions.
EcmaScript 7 (ES7), a newer version of Javascript came with several of such features, but in this article I will be focusing on one of them - Async/Await.

What is Async/Await?
After doing some research for a while, I figured out it is just another fancy way of writing asynchronous code which provides a nicer and cleaner way of writing async code in a synchronous manner.
Example of callback async code

fs.readFile(‘filename.txt’, (err, data) => {
  if (err) {
    // …handle error
  }
  // …make use of available data
})

The promise style would look something like

fs.readFile(‘filename.txt’)
  .then((data) => {
    // use the available returned data
  })
  .catch((err) => {
    // handle error
  })

With await/async

async function getFileDetails() {
  const data = await fs.readFile(‘filename.txt’)
  // use the result from the above available data 
}

From the above snippets, you will notice the different async code and see how the async/await code looks like a synchronous code.

Today we will be consuming github’s API via command line to get a user’s github detail using the new async/await syntax.
This tutorial assumes you have NodeJS and npm installed on your computer. So, let’s get started!

Create a new directory named async which will be the root of our application. cd into the directory and run this command npm init -y which would create a package.json file with some information pre-filled because of the inclusion of the -y flag.

Your package.json file should look like this

{
  "name": "async",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

The node version v6.10.3 (which I currently have installed) doesn’t support async/await as this feature is currently supported in ES7 and above. So we need to install babel to have access to the async/await functionality. Run

npm install —save-dev babel-cli babel-preset-env

in the command line to install babel-cli and also have the ability to use ES7 features by installing the babel-preset-env. For us to be able to configure babel, create a .babelrcfile and add the following

{
  "presets": "env"
}

We also need a way to consume Github’s API. This can be achieved using the built-in https module in NodeJs but to demonstrate the power of async/await I have decided to use an npm package request-promise. So run

npm install --save request request-promise

We needed to also install request as it is a peer dependency for request-promise. Having installed necessary npm packages, let’s go ahead and consume the API.

Create an index.js file in the root directory and add this snippet

import request from 'request-promise';

// github's username
const username = 'hajorg';

// request configuration
const options = {
  // the uri provided is the github's API endpoint to get a user's details
  uri: `https://api.github.com/users/${username}`,
  headers: {
    'User-Agent': 'Request-Promise'
  },
  json: true
};

// The async/await functionality
(async function () {
  try {
    const userDetails = await request(options);
    console.log(userDetails);
  } catch(err) {
    console.log(err.message);
  }
})()

So what is happening in the above snippet? First of all, we imported the request-promise package we installed earlier as request in other to use it to make an api call to github's api. The request function takes in a request object and returns a promise. Instead of using .then and .catch promise syntax, we use async/await. This is done by wrapping the request method in an anonymous function and the function declaration is prefixed with async keyword. In function, we created a variable to hold the result of the request method which returns a promise. With the help of the await keyword, we are able have our data saved to the userDetails variable. Incase an error occurrs, we wrapped our code within a try and catch block.

Open your package.json and add this to the scripts object

"start": "./node_modules/.bin/babel-node index.js",

Remember the babel-cli we installed earlier, we are going to use babel-node to run our index.js file. After inserting the above snippet, you can run npm start in the root of the application directory. After a second or so, you should get the result of the API call on the command line.

Note: using babel-node in production is not adviced. Check this link for more details.

The final package.json should now look like

{
  "name": "async",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "./node_modules/.bin/babel-node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-preset-env": "^1.6.0",
    "babel-preset-es2015": "^6.24.1"
  },
  "dependencies": {
    "request": "^2.81.0",
    "request-promise": "^4.2.1"
  }
}

There you have it, pretty cool and straightforward to use async/await. Just remember this to wrap a function with the async keyword and in the function, prefix the await keyword on the function that actually returns a promise and assign it to a variable.

If you have questions or feedback about this article, feel free to drop your thoughts in the comments section.

Discover and read more posts from Jorg Are
get started
Enjoy this post?

Leave a like and comment for Jorg

6
Be the first to share your opinion

Get curated posts in your inbox

Learn programming by reading more posts like this