Home >Web Front-end >JS Tutorial >My React Journey: Day 12
Practice with Callbacks andPromises
Today, I took on challenges to deepen my understanding of callbacks and promises—both foundational concepts for asynchronous programming in JavaScript. Here’s how it went:
Challenge 1: Callback - Event Registration Simulation
Scenario:
Simulated an event registration system where:
Code Implementation
// Event Data const event = { name: "React Masterclass", maxSlots: 5, currentRegistration: 3, }; // Registration Function function registerForEvent(event, user, successCallback, errorCallback) { console.log(`Registration of ${user} in progress...`); setTimeout(() => { if (event.currentRegistration < event.maxSlots) { event.currentRegistration++; successCallback(`Congratulations, ${user}. You have been registered for ${event.name}`); } else { errorCallback(`Sorry ${user}. The event space ${event.name} is fully booked`); } }, 2000); // Simulating 2-second delay } // Callbacks function onSuccess(message) { console.log("Success:", message); } function onError(error) { console.log("Error:", error); } // Simulate Registration registerForEvent(event, "Damilare", onSuccess, onError);
Output:
Reflection:
This challenge highlighted how callbacks handle asynchronous tasks, such as processing delays and managing outcomes.
Challenge 2: Promises - Delayed Welcome Message
Scenario:
Create a function that returns a welcome message after a specified delay using promises.
Code Implementation
// Promise Function function delayedWelcomeMessage(message, delay) { return new Promise((resolve, reject) => { if (delay <= 0) { reject("Delay must be greater than 0 milliseconds"); } else { setTimeout(() => { resolve(message); }, delay); } }); } // Valid Delay delayedWelcomeMessage("Welcome to the world of promises", 3000) .then((message) => console.log("SUCCESS:", message)) .catch((error) => console.error("ERROR:", error)); // Invalid Delay delayedWelcomeMessage("This will fail.", 0) .then((message) => console.log("SUCCESS:", message)) .catch((error) => console.error("ERROR:", error));
Output:
For a valid delay:
After 3 seconds:
SUCCESS: Welcome to the world of promises
For an invalid delay (e.g., 0):
ERROR: Delay must be greater than 0 milliseconds
Reflection:
This exercise reinforced how promises improve readability and manage asynchronous flows better than callbacks, especially when dealing with multiple steps.
Takeaways:
Callbacks: Useful for managing simple async operations but can get messy with nesting (callback hell).
Promises: Provide a cleaner, more scalable approach to handling async tasks.
Combining these challenges with real-world scenarios (like event registration) made the concepts more relatable and fun to practice.
I am excited!
The above is the detailed content of My React Journey: Day 12. For more information, please follow other related articles on the PHP Chinese website!