Async JavaScript Workshop, quizzes, demo, explanations, cheatsheets.
An in-depth tutorial on asynchronous JavaScript. From callbacks to promises (up to async/await pattern). Most advanced topic: iterators, generators, v8: node and chrome event loops.
Learning material from the Udemy Course of Asim Hussain.
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
In order to get the code up and running you need to have Node 10+ installed on your machine. VSCode is not necessary but it let's you run the selected node code pressing F8 with the "Node Exec" extension
Different async patterns, from basic to advance, starting from the fs.readFile node method.
const fs = require('fs');
const fileLoader = ['./files/demofile.txt', './files/demofile.other.txt'];
//Making a promise version of readFile
function readFile(filename, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(filename, encoding, (err, data) => {
if (err) reject(err);
resolve(data);
});
});
}
// STEP 1: Making a promise all for files with standard promises
let promises = fileLoader.map(file => readFile(file, 'utf8'));
Promise.all(promises)
.then(data => {
console.log(data);
})
.catch(err => console.log(err));
//STEP 2: Making a promise all for files with async await
(async () => {
for (let file of fileLoader) {
let value = await readFile(file, 'utf8');
console.log(value);
}
})();
//STEP 3: Resolve promises using generators
function* fileGenerator(files) {
for (let file of files) {
yield Promise.resolve(readFile(file, 'utf8'));
}
}
(async () => {
for await (let x of fileGenerator(fileLoader)) {
console.log(x);
}
})();