17.1 Asynchronous Programming Techniques (25 mins)
1. The Importance of Asynchronous Programming
Asynchronous programming allows JavaScript to:
Perform non-blocking operations, keeping the UI responsive.
Handle tasks like API calls, file reading, or animations without freezing the main thread.
Manage multiple simultaneous operations, such as fetching multiple datasets concurrently.
2. Common Asynchronous Programming Techniques
2.1 Using Callbacks
Scenario: You want to perform a task after another finishes.
Steps:
Define a function and pass another function (callback) as an argument.
Invoke the callback function when the task is complete.
Example:
function fetchData(callback) {
setTimeout(() => {
const data = 'Data fetched!';
callback(data);
}, 2000); // Simulate a delay of 2 seconds
}
fetchData((result) => {
console.log(result); // Logs: "Data fetched!"
});2.2 Using Promises
Promises simplify handling multiple asynchronous operations and chaining them in a more readable manner.
Steps:
Use a
Promiseconstructor to wrap an asynchronous task.Use
.then()to handle success and.catch()to handle errors.
Example:
Key Points:
resolve: Called when the operation succeeds.reject: Called when the operation fails.
2.3 Using Async/Await
Async/Await allows for writing asynchronous code in a synchronous style.
Steps:
Define a function with the
asynckeyword.Use the
awaitkeyword to pause execution until the promise resolves.
Example:
3. Combining Techniques
Chaining Promises: When multiple tasks depend on each other.
Parallel Execution with
Promise.all: UsePromise.allto execute multiple asynchronous tasks in parallel and wait for all of them to complete.
Student Activity
Objective: Practice and demonstrate the use of callbacks, promises, and async/await.
Activity 1: Chaining Promises
Task:
Create two functions,
getUserDetailsandgetUserPosts, that simulate fetching user details and their posts.Use promise chaining to first fetch user details, then their posts.
Template:
Activity 2: Refactoring with Async/Await
Task: Refactor the solution from Activity 1 to use async/await.
Template:
Expected Learning Outcomes:
Understand how to chain asynchronous operations using promises.
Use async/await to simplify asynchronous workflows.
Recognize scenarios where parallel execution (
Promise.all) is useful.
Last updated