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! 🚀😊
Top comments (0)