Understanding asynchronous call in Node.js — async and await

Photo by Ferenc Almasi on Unsplash

As explained in this post, Node.js’ performance will be very good if the source code this framework will run is asynchronous. This is why, starting from version 6, ECMAScript language (the “father” of Javascript, and then of Node.js) adds some “programmer’s help” to make more easy-to-read an asynchronous code (e.g promises).
Starting from ECMAScript 8, a new syntax was added: async and await.

async is a keyword to be added in function declaration and mean that the function is asynchonous, while await is a keyword to be used when an asynchonous function will be invoked, allowing to assign function result to a variable like synchronous functions.
The only cons about using these two keywords is the use of try-catch block to catch errors, despite promises' catch function.

So, what with promises will be written like

fs.readFile(nameFile).then(function(response) {
return readLine(response);
}).then(function(line){
...
}).catch(function(error){
...
});

with async and await will be written like

async function readFile(content) {
...
}
try {
const response = await fs.readFile(nameFile);
const line = await readLine(response);
...
} catch (error) {
...
}

Originally published at https://gabriele-decapoa.github.io.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriele de Capoa

Gabriele de Capoa

11 Followers

Cloud software engineer, wanna-be data scientist, former Scrum Master. Agile, DevOps, Kubernetes and SQL are my top topics.