๐ Unraveling Asynchronous JavaScript: Dive Into Promises, Async/Await, and Beyond! ๐
Asynchronous JavaScript is the cornerstone of modern web development, enabling complex operations like data fetching, timer-based actions, and parallel processing without blocking the main thread.
To boost our collective journey into this crucial JavaScript feature, I’ve crafted a series of exercises:
– Grasp the core concepts of `setTimeout`, Promises, and the Fetch API.
– Delve into advanced topics such as error handling, promise chaining, and async/await.
– Elevate your skills with parallel execution techniques using `Promise.all`.
Why master asynchronous JavaScript?
– Itโs pivotal for creating smooth, responsive web applications.
– Deep understanding paves the way for better error handling and data retrieval strategies.
– It aligns with the industryโs shift towards more asynchronous programming patterns.
I invite you to tackle these challenges, share your solutions, or pose questions. Letโs foster a vibrant community discussion and unravel the intricacies of asynchronous JavaScript together!
#JavaScript #AsynchronousJavaScript #WebDevelopment #CodingExercises #LearnToCode
Embrace the async journey! ๐๐จโ๐ป๐ฉโ๐ป
Exercise 1: Basic setTimeout
Problem: Use setTimeout to print “Hello, JavaScript!” to the console after 3 seconds.
Explanation: Demonstrates basic usage of setTimeout, which delays execution of a function by a specified number of milliseconds.
Code:
setTimeout(() => {
console.log(“Hello, JavaScript!”);
}, 3000);
Exercise 2: clearTimeout Usage
Problem: Start a timeout to execute after 5 seconds, but cancel it before it executes.
Explanation: Shows how to cancel a timeout, preventing the function passed to setTimeout from being called if the timeout is cleared before it expires.
Code:
let timeoutId = setTimeout(() => {
console.log(“You won’t see this message!”);
}, 5000);
clearTimeout(timeoutId);
Exercise 3: Basic Promise
Problem: Create a Promise that resolves with “Success” after 2 seconds and print the result using .then().
Explanation: Introduces creating a new Promise and using .then() to handle its resolution.
Code:
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(“Success”);
}, 2000);
});
myPromise.then((message) => {
console.log(message); // Outputs: “Success”
});
Exercise 4: Handling Promise Rejection
Problem: Create a Promise that rejects with an error message “Failed!” after 1 second and handle the error using .catch().
Explanation: Demonstrates handling of Promise rejection, which is important for error handling in asynchronous operations.
Code:
let failingPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(“Failed!”);
}, 1000);
});
failingPromise.catch((error) => {
console.error(error); // Outputs: “Failed!”
});
Exercise 5: Chaining Promises
Problem: Chain two promises where the first resolves with a number, then the second promise doubles that number.
Explanation: Teaches chaining promises using .then(), which allows for sequential asynchronous operations.
Code:
let firstPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(10);
}, 1000);
});
firstPromise.then((number) => {
return number * 2;
}).then((result) => {
console.log(result); // Outputs: 20
});
Exercise 6: Async/Await Basic Usage
Problem: Create an async function that awaits a Promise resolved with “Async/Await” after 3 seconds and prints the result.
Explanation: Introduces the async/await syntax as a cleaner alternative to .then() for handling Promises.
Code:
async function myAsyncFunction() {
let message = await new Promise(resolve => {
setTimeout(() => {
resolve(“Async/Await”);
}, 3000);
});
console.log(message); // Outputs: “Async/Await”
}
myAsyncFunction();
Exercise 7: Handling Errors in Async/Await
Problem: Use a try-catch block in an async function to handle rejection from a Promise that rejects with “Error!” after 2 seconds.
Explanation: Shows error handling in async/await syntax, crucial for managing exceptions in asynchronous operations.
Code:
async function errorHandlingFunction() {
try {
let result = await new Promise((resolve, reject) => {
setTimeout(() => {
reject(“Error!”);
}, 2000);
});
console.log(result);
} catch (error) {
console.error(error); // Outputs: “Error!”
}
}
errorHandlingFunction();
Exercise 8: Fetch API Usage
Problem: Use the Fetch API to retrieve data from “https://jsonplaceholder.typicode.com/posts/1” and print the title of the post.
Explanation: Teaches how to use the Fetch API with Promises to retrieve data from a server.
Code:
fetch(‘https://jsonplaceholder.typicode.com/posts/1’)
.then(response => response.json())
.then(post => console.log(post.title))
.catch(error => console.error(‘Error:’, error));
Exercise 9: Async/Await with Fetch
Problem: Use async/await syntax to retrieve data from “https://jsonplaceholder.typicode.com/posts/1” and print the post’s title.
Explanation: Combines async/await with the Fetch API for more readable asynchronous code involving HTTP requests.
Code:
async function fetchPostTitle() {
try {
let response = await fetch(‘https://jsonplaceholder.typicode.com/posts/1’);
let post = await response.json();
console.log(post.title);
} catch (error) {
console.error(‘Error:’, error);
}
}
fetchPostTitle();
Exercise 10: Parallel Promises with Promise.all
Problem: Execute two Promises in parallel, both resolving after different durations, and print their results together.
Explanation: Demonstrates the use of Promise.all for running multiple asynchronous operations in parallel.
Code:
let promise1 = new Promise(resolve => setTimeout(() => resolve(“First promise”), 2000));
let promise2 = new Promise(resolve => setTimeout(() => resolve(“Second promise”), 1000));
Promise.all([promise1, promise2]).then((results) => {
console.log(results); // Outputs: [“First promise”, “Second promise”]
});