17.4 Homework Assignment (15 mins)
Objective:
Students will apply the concepts of asynchronous programming, including callbacks, promises, and async/await, to simulate real-world tasks. This assignment reinforces the topics covered in the lecture and programming activities.
Assignment Task:
Create a JavaScript program that simulates the following sequence of asynchronous tasks:
Fetch user profile (Simulate fetching a user profile with a delay).
Fetch user posts (Simulate fetching a user's posts after the profile is fetched).
Fetch user comments (Simulate fetching comments for a specific post).
Implement the solution using:
Callbacks
Promises
Async/Await
Step-by-Step Procedure for Programming Activity
1. Setup the Asynchronous Tasks
Simulate the following functions using setTimeout:
fetchUserProfile: Resolves after 1 second with a user object.fetchUserPosts: Resolves after 2 seconds with an array of posts for the user.fetchPostComments: Resolves after 1.5 seconds with an array of comments for a post.
2. Task 1: Implement Using Callbacks
Use nested callbacks to execute the tasks sequentially:
Fetch the user profile.
Fetch posts for the user.
Fetch comments for the first post.
Solution:
3. Task 2: Refactor Using Promises
Modify the task functions to return promises instead of accepting callbacks:
Solution Using Promises:
4. Task 3: Refactor Using Async/Await
Use async/await to make the program more readable:
Create an
asyncfunction to execute the tasks sequentially.Use
try...catchfor error handling.
Solution Using Async/Await:
Assignment Deliverables:
A single JavaScript file (
asynchronous.js) containing:The callback-based implementation.
The promise-based implementation.
The async/await implementation.
Expected Outcomes:
Students will learn to handle asynchronous tasks sequentially using different techniques.
They will compare and contrast callbacks, promises, and async/await in terms of readability and error handling.
Gain hands-on experience in refactoring code for improved maintainability.
Last updated