Notes

Intro to Asynchronous JS

Synchronous vs Asynchronous Code

Can’t believe it’s async?

Why do we need asynchronous code?


Timeouts and Intervals

function foo() {
  console.log("food");
}

setTimeout(foo, 2000);
console.log("drink");
function foo(food1, food2) {
  console.log(food1 + " for breakfast");
  console.log(food2 + " for lunch");
}

setTimeout(foo, 2000, "pancakes", "couscous");

Cancelling Timeouts

function foo() {
  console.log("food");
}

const val = setTimeout(foo, 2000);
console.log(val);

clearTimeout(val);

Running Intervals

function foo(food1, food2) {
  console.log(food1 + " and " + food2 + "!");
}

setInterval(foo, 1000, "pancakes", "couscous");

Threading

pic of thread
pic of thread

Single-threaded vs multi-threaded execution

Keeping the Thread from Unraveling


The Call Stack

The Practical Consequences of the Call Stack


The Message Queue and Event Loop

Javascript is the tool that enables web pages to be interactive and dynamic.

The Event Loop

The Message Queue

illust of event loop
illust of event loop

User Input with Readline

Node’s readline module

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question("What's up, doc? ", (answer) => {
  console.log("you responded: " + answer);
  rl.close();
});

// try to print 'DONE!' after the question
console.log("DONE!");

Callback Chaining

rl.question("What's up, doc? ", (answer) => {
  console.log("you responded: " + answer);
  rl.close();
  console.log("DONE!");
});

Example of messy code

// this code is a partial snippet from previous examples

rl.question("What's up, doc? ", (firstAnswer) => {
  console.log(firstAnswer + " is up.");

  rl.question("What's down, clown? ", (secondAnswer) => {
    console.log(secondAnswer + " is down.");

    rl.question("What's left, Jeff? ", (thirdAnswer) => {
      console.log(thirdAnswer + " is left.");
      rl.close();
    });
  });
});

How it looks after it has been refactored

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question("What's up, doc? ", handleResponseOne);

function handleResponseOne(firstAnswer) {
  console.log(firstAnswer + " is up.");
  rl.question("What's down, clown? ", handleResponseTwo);
}

function handleResponseTwo(secondAnswer) {
  console.log(secondAnswer + " is down.");
  rl.question("What's left, Jeff? ", handleResponseThree);
}

function handleResponseThree(thirdAnswer) {
  console.log(thirdAnswer + " is left.");
  rl.close();
}