Async await

Learn how to take advantage of async and await reserved keywords.

What’s the meaning of async and await?

A function preceded by async returns a promise. The term await precedes an asynchronous action and returns the value that would solve that function. If any of the await fails (its promise was rejected) it means that async function returned a rejected promise.

Usage example

Here is an example of code using promises and its translation into code which uses async + await.

Example using promises

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const getItem = email => {
const promise = new Promise((resolve,reject) => {
User.findOne({email})
.then(user => Car.findOne({owner: user.card}))
.then(car => Catalog.findOne({ref: car.model}))
.then(item => resolve(item))
.catch(error => reject(error));
});

return promise;
};

getItem('[email protected]')
.then(console.log)
.catch(console.error);

Example using async/await

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const getItem = async email => {

try {

const user = await User.findOne({email});
const car = await Car.findOne({owner: user.card});
const item = await Catalog.findOne({ref: car.model});

return item;

} catch (error){

return Promise.reject(error)

}
};

getItem('[email protected]')
.then(console.log)
.catch(console.error);

Note

You can never use await outside a function not preceded by async. You can never use await at the highest level. So in the example above we cannot do this:

1
const item = await getItem ('[email protected]');

You should always use try/catch, this way we’ll capture any error generated by any await. If your promise doesn’t return anything just finish your function adding return;.

Compatibility with Node.js

It’s needed to have Node.js >= 8.0.0 to support it officially. Regarding to front-end technologies, browsers, etc…. I understand that it is widely supported but I recommend to use a transpiler such webpack.

References