Notes

[ES2015] Async/Await Functions

Edit on GitHub

JavaScript
2 minutes

Async/Await Functions

declare an async function that will allow us to wait for other functions. we can only await inside an async function, and we can only await a promise.

Async/await is an ES2016 (ES7) feature, so you’ll need a transpiler. See http://babeljs.io/docs/plugins/preset-latest/

1npm i -g babel-cli

add a minimal .babelrc inside your project dir

1{
2  "presets": [
3    "latest"
4  ]
5}

and install packages (locally, inside your project folder)

1npm install --save-dev babel-preset-latest

Once setup, you can run from CLI

1babel-node script.js

We are going to use the JS builtin .fetch API for our example, but others like axios can also be used, any lib that returns a promise.

1npm i -D node-fetch
 1import fetch form 'node-fetch'
 2// Async/Await Example
 3
 4const service = {
 5	getUsers: () => fetch('https://jsonplaceholder.typicode.com/users'),
 6	getPosts: () => fetch('https://jsonplaceholder.typicode.com/posts')
 7}
 8
 9// Await a promise to fulfill and do something
10async function Fetchy() {
11	try {
12		const users = await service.getUsers()
13		const posts = await service.getPosts()
14
15		console.log('Example: Fetchy', {
16			Users: users.data,
17			Posts: posts.data
18		})
19
20	} catch(err) {
21		console.warn('ERROR', err)
22	}
23}
24
25Fetchy()
26
27// Await all promises to fulfill
28async function FetchyAll() {
29	try	{
30		const values = await Promise.all([ service.getUsers(), service.getPosts() ])
31		console.info('Example: FetchyAll', values.map(v => v.data))
32
33	} catch(err) {
34		console.warn(err)
35	}
36}
37
38FetchyAll()

You can only await on async functions from within other async functions.

Related