frivolta / async-javascript-patterns

Async JavaScript Workshop, quizzes, demo, explanations, cheatsheets.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Async JavaScript Workshop

Status


Async JavaScript Workshop, quizzes, demo, explanations, cheatsheets.

πŸ“ Table of Contents

🧐 About

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.

🏁 Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

Prerequisites

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

🎈 Extract example

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);
    });
  });
}

First implementation with standard Promises syntax

// 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));

Second implementation using async await IIFE

//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);
  }
})();

Third implementation using generators to iterate and resolve promises

//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);
  }
})();

🎈 Event loops CheatSheet

This is a simplyfied version of the node event loop:

An example code of the above schema:

A simplyfied version of the v8 Chrome event loop:

About

Async JavaScript Workshop, quizzes, demo, explanations, cheatsheets.


Languages

Language:HTML 73.5%Language:JavaScript 22.9%Language:CSS 3.6%