Credit to Simon Haddad for being a key part of preparing this lecture
Whilst promises are an improvement from callbacks, they can still create unnecessarily verbose code for trying to use async code synchronously in simple ways.
So a new syntax was created in ES2017 (now supported by virtually all browsers) to help this.
const fs = require('fs').promises;
const readFiles = async () => {
let data = '';
try {
data = await fs.readFile('chapter1.txt', 'utf-8');
console.log('Chapter 1: ', data);
} catch (err) {
console.log('Error: ', err);
}
};
readFiles();
const fs = require('fs').promises;
const files1 = fs.readFile('chapter1.txt', 'utf-8')
files1
.then(data => {
console.log('Chapter 1: ', data);
})
.catch(err => {
console.log('Error: ', err);
});
This is a very basic comparison of the two in action.
const fs = require('fs').promises;
const readFiles = async () => {
let data = '';
try {
data = await fs.readFile('chapter1.txt', 'utf-8');
console.log(data);
data = await fs.readFile('chapter2.txt', 'utf-8');
console.log(data);
data = await fs.readFile('chapter3.txt', 'utf-8');
console.log(data);
data = await fs.readFile('chapter4.txt', 'utf-8');
console.log(data);
data = await fs.readFile('chapter5.txt', 'utf-8');
console.log(data);
} catch (err) {
console.log(err);
}
};
readFiles();
const fs = require('fs').promises;
const files1 = fs.readFile('chapter1.txt', 'utf-8')
files1
.then(data => {
console.log('Chapter 1: ', data);
return fs.readFile('chapter2.txt', 'utf-8')
})
.then(data => {
console.log('Chapter 2: ', data);
return fs.readFile('chapter3.txt', 'utf-8')
})
.then(data => {
console.log('Chapter 3: ', data);
return fs.readFile('chapter4.txt', 'utf-8')
})
.then(data => {
console.log('Chapter 4: ', data);
return fs.readFile('chapter5.txt', 'utf-8')
})
.then(data => {
console.log('Chapter 5: ', data);
})
.catch(err => {
console.log('Error: ', err);
});
The benefit of async/await becomes more noticeable when doing substantially more async calls that you want to process linearly.