Promises and callback function

In the following code:

const fs = require('fs'); const promisifiedReadfile = require('./promisifiedReadfile'); // Here we use fs.readfile() and callback functions: 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); }); }); function readFiles() { let firstSentence = promisifiedReadfile('./file.txt', 'utf-8'); let secondSentence = promisifiedReadfile('./file2.txt', 'utf-8'); console.log(firstSentence, secondSentence); } console.log("test") readFiles();

From this exercise (I edited the code a little bit)
Why the result of callback function readFile is printed in the end?? isn’t this method is a synchronous, and supposed to be printed first, since it’s in the top?
and thanks.

Hey! Yes, fs.readFile is asynchronous, so it prints after readFiles() which is not asynchronous in your example.

You can add async/await to readFiles() to make it asynchronous (it will not return Promise { <pending }).

console.log("test") will always appear first, before the asynchronous actions.


Highly recommend this book’s chapter on async

1 Like

Title sounds interesting, I’ll check it out surely!