FAQ: Async Await - Introduction

This community-built FAQ covers the “Introduction” exercise from the lesson “Async Await”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Asynchronous JavaScript
Asynchronous JavaScript

FAQs on the exercise Introduction

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

I’m looking at line 1 of the app.js:

const fs = require(‘fs’);

It is requiring in “fs”, but I can’t find where that is coming from. My understanding was that require() would import a module from another file. Is that correct? If so, I’m unclear of how this works in this instance.

10 Likes

It looks like this is something available through Node. I found this in the Node documentation:

The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.

To use this module:

const fs = require('fs');

They also have info about the readFile method.

10 Likes

Can someone tell me please what is the Callback function in the first part of the code (Lines 5 - 13) in app.js.

1 Like

Yes, can someone explain a bit 5-13? Thanks!

fs.readFile(’./file.txt’, ‘utf-8’, (err, data) => {
if (err) throw err;
let firstSentence = data;
fs.readFile(’./file2.txt’, ‘utf-8’, (err, data) => {
if (err) throw err;
let secondSentence = data;
console.log(firstSentence, secondSentence)
});
});

1 Like
fs.readFile(’./file.txt’, ‘utf-8’, (err, data) => {

This line reads a file file.txt in the working directory (./) in the unicode. The third argument specifies a callback function, the function to be executed once reading the file is done.

if (err) throw err;

If there is an error while reading the file, the callback function’s first argument err will be true. So this line will be executed to throw an error (an error message will be printed in the console). And the rest of the code will be ignored.

let firstSentence = data;

The callback function’s second argument data will be the file content if reading the file is successfully done. We store the file content as the variable called firstSentence.

fs.readFile(’./file2.txt’, ‘utf-8’, (err, data) => {

This is the same as the first line except for the file: it will read file2.txt.

if (err) throw err;

This is the same as the second line. If reading file2.txt fails, an error message will be shown in the console. And the rest of the code will be ignored.

let secondSentence = data;

This line stores the file2.txt’s content as the variable secondSentence.

console.log(firstSentence, secondSentence)

The file content from file1.txt and file2.txt will be shown in the console.

14 Likes

My question concerns the second art of the code (lines 16 - 26:

let firstSentence
promisifiedReadfile(’./file.txt’, ‘utf-8’)
.then((data) => {
firstSentence = data;
return promisifiedReadfile(’./file2.txt’, ‘utf-8’)
})
.then((data) => {
let secondSentence = data;
console.log(firstSentence, secondSentence)
})
.catch((err) => {console.log(err)});

In the first line, firstSentence is declared outside of the promise object chain and then assigned a value within the object chain. Would it not be cleaner to declare the variable and assign it a value within the object, like in the first part of the code?

But more importantly, I don’t understand how the promise is created. Codecademy teaches us that a new Promise must be created first and that it can only contain an executor function as parameter. But in this example, promisifiedReadfile shows up out of nowhere with both success and failure parameters. How does JS understand that this is a promise, other than it being followed by .then?
Why doesn’t this result in an error? And if this is indeed a proper method of creating a new promise, why was this not taught in the the earlier lessons and exercises?

I look at this part of the code and it seems completely wrong to me, as it does not follow what we’ve learned so far.

3 Likes

I think that the firstSentence variable is declared outside the local scope of the first .then() — in global scope — because otherwise we wouldn’t be able to access it when logging both sentences to the console in the second .then() .

At the top of app.js ,  promisifiedReadfile is imported as a module from the file with the same name, using the following code:

const promisifiedReadfile = require('./promisifiedReadfile');

Unfortunately, when this exercise loads, promisifiedReadfile.js is hidden. To view the file, click the file icon in the top left hand corner of the code-editor where you will find a list of all four files used in this exercise. Click on promisifiedReadfile.js  and you will then be able to view it in the code-editor. Here you will find the function which constructs the promise and contains the executor function, both of which you quite rightly expected to see… :wink:

3 Likes

i found this https://www.geeksforgeeks.org/node-js-fs-readfile-method/ to be VERY usefull

4 Likes

Thanks! It was really helpful.

fs is actually a node module. fs stands for File System, and it allows us to work with files. As you saw in the lesson, we used the fs module to read the text in the file

The instructions about “you’ll be given… a bash terminal to execute your code.” are excellent.

I wonder whether all this course would gain in quality if these instructions were moved up to the lesson 5 of chapter “Transpilation”. At that lesson, the learner was brutally dropped into using the terminal without much explanations.

My 2 cents…

How is the promise function working without using the return keyword before new? And why is return used before the reject. I’ve not seen that before.

const promisifiedReadfile = (file, encoding) => 
  new Promise((resolve, reject) => {
    fs.readFile(file, encoding, (err, text) => {
			if (err) {
				return reject(err.message);
      }
        resolve(text);
      });
});
1 Like

Answering your first question: This is arrow function syntax. If you only want to return something in the function body (i.e., withing the braces { } ), then you can just omit the braces and the return keyword. Review the JavaScript Beginner course on arrow.

Hi, I was looking at this introduction and I noticed that the result of “promisifiedReadfile(‘./file.txt’, ‘utf-8’)” is assigned to the variable “firstSentence”. If you check the type of “firstSentence” it says that it is a string but I believe that “promisifiedReadfile” returns a Promise. Can someone explain it to me?

async function readFiles() {
let firstSentence = await promisifiedReadfile(‘./file.txt’, ‘utf-8’);
console.log(typeof firstSentence);
let secondSentence = await promisifiedReadfile(‘./file2.txt’, ‘utf-8’);
console.log(typeof firstSentence);
console.log(firstSentence, secondSentence);
}