Node.js – Async/Await

By | 04/05/2022

In this post, we will see how to use Async/Await in Node.js for working in asynchronous mode in the easiest way.
It has been introduced from ES2017 to solve the complexities we can find using Promises.

For example, if we want to create a method to calculate the square of a number, using Promises, this is the code:

function double(x){
    return new Promise(result =>{
        setTimeout(() => {
            result(x*x)
        },2000)
    })
}

function PrintDouble(x)
{
    double(x).then(result =>{
        console.log(result);
    })
}


PrintDouble(10);


If we run the code, this will be the result:


It works fine but, if we use Async/Await, we could optimize the code in this way:

function double(x){
    return new Promise(result =>{
        setTimeout(() => {
            result(x*x)
        },2000)
    })
}

async function PrintDouble(x){
    console.log(await double(10));
}

PrintDouble(10);


If we run the code, we will have the same result:



For other information about Async/Await, we can go to:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


In the post: Node.js – How to manage files (Create, Modify and Delete a file), we have seen how to manage files with Node.js.
Now, we will see how to optimize that code using Async/Await:

READ FILE

const fsPromises = require('fs').promises;
const path = require('path');

async function readFile(fileName){
    try {
        const data = await fsPromises.readFile(path.join(__dirname, fileName), 'utf8');
        console.log(data);
    } catch (error) {
        console.log(error);
    }
}

readFile('test.txt');


WRITE FILE

const fsPromises = require('fs').promises;
const path = require('path');

async function readFile(fileName){
    try {
        const data = await fsPromises.readFile(path.join(__dirname, fileName), 'utf8');
        console.log(data);
    } catch (error) {
        console.log(error);
    }
}

async function writeFile(fileName) {
    try {
        await fsPromises.writeFile(path.join(__dirname, fileName), 'New File!!');
        console.log('>>Write File<<');
    } catch (error) {
        console.log(error);
    }
}

writeFile('test2.txt')
readFile('test2.txt');


APPEND FILE

const fsPromises = require('fs').promises;
const path = require('path');

async function readFile(fileName){
    try {
        const data = await fsPromises.readFile(path.join(__dirname, fileName), 'utf8');
        console.log(data);
    } catch (error) {
        console.log(error);
    }
}

async function appendFile(fileName){
    try {
        await fsPromises.appendFile(path.join(__dirname, fileName), '\nNew File2!!');
        console.log('Append File');
    } catch (error) {
        console.log(error);
    }
}

appendFile('test2.txt')
readFile('test2.txt');


DELETE FILE

const fsPromises = require('fs').promises;
const path = require('path');

async function deleteFile(fileName){
    try {
        await fsPromises.unlink(path.join(__dirname, fileName));
        console.log('Delete File');
    } catch (error) {
        console.log(error);
    }
}

deleteFile('test2.txt');



Leave a Reply

Your email address will not be published. Required fields are marked *