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:
Writing functions to perform asynchronous tasks.
Implementing callbacks, promises, and async/await.
Comparing the readability and usability of each approach.
Task: Simulate a Bookstore Operations
Simulate the following asynchronous operations:
Get list of books: Fetch a list of available books (simulate with a delay).
Get book details: Fetch details of a selected book (simulate with a delay).
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:
Fetch the list of books.
Select a book and fetch its details.
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
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:
Students will understand the differences in readability and usability of callbacks, promises, and async/await.
Students will be able to simulate asynchronous operations and handle errors effectively.
Gain hands-on experience in refactoring asynchronous code for improved maintainability.
Last updated