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:

  1. 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).

  2. 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:

  1. Fetch the user profile.

  2. Fetch posts for the user.

  3. 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:

  1. Create an async function to execute the tasks sequentially.

  2. Use try...catch for error handling.

Solution Using Async/Await:


Assignment Deliverables:

  • A single JavaScript file (asynchronous.js) containing:

    1. The callback-based implementation.

    2. The promise-based implementation.

    3. The async/await implementation.


Expected Outcomes:

  1. Students will learn to handle asynchronous tasks sequentially using different techniques.

  2. They will compare and contrast callbacks, promises, and async/await in terms of readability and error handling.

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

Last updated