Week 10 - Asynchronous programming

Synchronous vs Asynchronous Code

Callbacks

Promises

Asynchronous File I/O

Event Loop

Fetch API

Async/Await and Promise.all()

AI Using GitHub Copilot in VS Code

Practice

Assignment

Back to core program

Let’s get practical

<aside> 🚧

This page is currently under construction. Please check back later.

</aside>

Exercise 1: Create a traffic light with setInterval()

In this exercise you will create a traffic light that repeatedly cycles through its three states: GO, WAIT, and STOP. After four full cycles, the simulation should stop.

traffic-light-1.gif

Setup & Configuration

Instructions

The provided code already includes an object that models a traffic light and a function that updates the model and writes its current state to the console.Your job is to implement the TODO in the body of the main() function, such that you obtain the same result as shown in the animation above.

Exercise 2: Create a traffic light with setTimeout()

In real traffic lights, the time for each state is not the same. GO is followed by a shorter WAIT and a longer STOP. In this exercise we will try and simulate a traffic light with different times for each state. It should look like this:

traffic-light-2.gif

Instructions

  1. In the same src folder, create a file traffic-light-2.js. Paste in the code from the block below, then replace the abbreviated parts with the full code from the previous exercise.
  2. Your job is to implement the TODO in the body of the main() function, such that you obtain the same result as shown in the animation above.

Exercise 3: Create a traffic light with async/await

In this exercise, you should obtain the same result as in exercise 2, but now using promises and async/await. This helps you escape from “callback hell” and greatly simplifies the code.

Instructions

  1. Create a new file traffic-light-3.js in the src folder and paste in the code from the code block below. Replace the abbreviated code with the full code from the previous exercise.
  2. Your job is to implement the two TODOs, such that you obtain the same result as shown in the animation from exercise 2.

Exercise 4 - Deck of Cards Application

From the Learning-Resources repository, follow the instructions from the README in the link below to complete the fetch logic of the Deck Of Cards application:

https://github.com/HackYourFuture/Learning-Resources/tree/main/core-program/week-10/deck-of-cards


CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*

Found a mistake or have a suggestion? Let us know in the feedback form.