Programming Foundations: From Algorithms to JavaScript

Introduction to Asynchronous JavaScript

Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

25 min

Why Asynchronous Programming Exists

Represent a result that is not available yet

By the end of this lesson

  • Represent a result that is not available yet
  • Predict immediate work versus later callbacks

A request is not its result

A quote may need a delivery charge supplied later. Starting the request does not mean the amount is available. Before choosing syntax, define what the program can do now and what must wait.

We will simulate later work locally. No real server, HTTP or account is required. The browser provides setTimeout, a timer facility outside the core JavaScript language.

console.log("Start");
setTimeout(() => {
  console.log("Later result");
}, 0);
console.log("Continue");

Predict Start, Continue, Later result. A zero delay does not mean interrupt the current code immediately. The callback becomes eligible to run later, after current synchronous work and other scheduling constraints. Timers do not promise exact execution times.

Guided review

Putting a variable assignment inside the timer and reading it immediately afterward still reads the earlier value. The source file's visual order does not mean the timer callback has already executed. The dependent work belongs after completion, not merely after the request statement.

This example is only a scheduling demonstration. We will use promises next to give a later result a clear success/failure contract.

Independent exercise

Add a message inside the callback before its result, and another immediate message after Continue. Write the complete order before running. Then explain why increasing the timer delay changes waiting time but not the relative order of the immediate statements.

Correction

All immediate messages finish first in their written order. The callback's messages appear together afterward in their own order. A longer delay postpones eligibility; it does not make synchronous statements wait for the callback.

Review

Asynchronous work introduces a temporal dependency: use the value only once the operation supplying it has completed. It does not eliminate the need to understand the rule or validate the eventual value.

Lesson complete?

Your progress is saved on this device.