Daily : Wed 3 July : Promises & Async/Await

AlessandroAlessandro
1 min read

Hello,

Still on my quest to master all the crucial mechanisms of JavaScript! ๐ŸŒŸ

Recently, I found myself wrestling with when to use promises versus async/await functions. This morning, I decided to dive deeper into the topic.

Thanks to Bro Code - YouTube (seriously, check out his work, it's fantastic! ๐Ÿ˜‰), the concept was clearly explained. Writing synchronous code in an asynchronous way? Sounds pretty cool, right?

Suddenly, it all started to click. Learning JavaScript can feel like navigating a maze with its myriad concepts, but breaking it down like this helps a lot.

I tried my hand at writing some code to better understand how we can use async/await with promises written by others. The code takes a file.txt as input, containing several lines of text, which I'll split into an array and then parse using a for...of loop.

Here's the code:

import fs from 'node:fs/promises';

async function readInput(input) {
    try {
        const content = await fs.readFile('file.txt', 'utf-8');
        return content;
    } catch (error) {
        console.error(error);
    }
}

const output = await readInput();
for (const line of output.split('\n')) {
    console.log(line);
}

This makes a lot of sense when reading the documentation and seeing the promise return. Now, I have a simple and readable way to handle this promise.

Cheers and happy coding! ๐Ÿš€๐Ÿ˜Š

0
Subscribe to my newsletter

Read articles from Alessandro directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alessandro
Alessandro