DEV Community

Alessandro
Alessandro

Posted on • Originally published at blog.lamparelli.eu on

Daily : Wed 3 July : Promises & Async/Await

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);
}
Enter fullscreen mode Exit fullscreen mode

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! 🚀😊

👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay