17.3 Programming Activity: Asynchronous Programming Practices (20 mins)

Objective:

Illustrate key concepts of asynchronous programming by writing JavaScript programs that simulate real-world tasks using callbacks, promises, and async/await.

Students will practice:

  1. Writing functions to perform asynchronous tasks.

  2. Implementing callbacks, promises, and async/await.

  3. Comparing the readability and usability of each approach.


Task: Simulate a Bookstore Operations

Simulate the following asynchronous operations:

  1. Get list of books: Fetch a list of available books (simulate with a delay).

  2. Get book details: Fetch details of a selected book (simulate with a delay).

  3. Place an order: Place an order for the selected book (simulate with a delay).

Students will implement these operations using:

  • Callbacks

  • Promises

  • Async/Await


Step-by-Step Procedures

1. Setup the Asynchronous Task Functions

Define three asynchronous functions using setTimeout to simulate delays:


2. Task 1: Using Callbacks

Implement the operations using nested callbacks:

  1. Fetch the list of books.

  2. Select a book and fetch its details.

  3. Place an order for the selected book.

Solution:


3. Task 2: Refactor Using Promises

Modify the task functions to return promises instead of using callbacks:

Solution Using Promises:


4. Task 3: Refactor Using Async/Await

Use async/await to make the code more readable and linear.

Solution Using Async/Await:


Comparing the Techniques

Technique
Pros
Cons

Callbacks

Simple and easy for one or two tasks.

Callback hell for nested tasks.

Promises

Handles chaining and errors cleanly.

Slightly more verbose than async/await.

Async/Await

Linear and synchronous-like code flow.

Requires modern JavaScript support.


Expected Outcomes:

  1. Students will understand the differences in readability and usability of callbacks, promises, and async/await.

  2. Students will be able to simulate asynchronous operations and handle errors effectively.

  3. Gain hands-on experience in refactoring asynchronous code for improved maintainability.

Last updated