Task 14: Understanding JavaScript Promises with .then() and .catch()
Start with Thanksgivingβ
I declare that gratitude overflows in my life.
I declare that I am thankful for what I have, and excited for what's coming.
I declare that every blessing in my life multiplies as I remain thankful.
I declare that I walk in abundance, not because of what I have, but because of who I serve.
I declare that today I choose joy, contentment, and peace.
I declare that my heart is full of gratitude and my mouth speaks life.
I declare that thankfulness opens doors no man can shut.
I declare that I am a magnet for miracles because I choose gratitude.
I declare that I will see Godβs goodness in new ways this season.
I declare that I give thanks in all things, and trust His timing in everything.
πͺ Repeat daily, feel the power, and watch your success unfold!
Task Answer - Video Linkβ
πΉ If you donβt understand the task, watch the video above for the answer.
Taskβ
β Promises! Weβll keep it simple and fun β by the end of this video, youβll know:
- β What a Promise is
- β How to use .then() and .catch()
- β And weβll build a mini app to fetch a random dog photo πΆ using an API!" Letβs get started! π
** Step 1: What is a Promise?β
A Promise in JavaScript is like a real-world promise. You ask for something (like a dog pic), and JavaScript promises to deliver it later β either:
- β It resolves with success (Yay, we got the photo!)
- β Or it rejects with an error (Oops, something went wrong!)
Step 2: Using fetch() with .then() and .catch()β
Letβs use the Dog CEO API to get a random dog photo and handle it with .then() and .catch().
// 1. Make the request
fetch("https://dog.ceo/api/breeds/image/random")
// 2. Convert the response to JSON
.then(response => response.json())
// 3. Use the data
.then(data => {
console.log("πΆ Dog image URL:", data.message);
})
// 4. Handle errors
.catch(error => {
console.error("Oops! Something went wrong:", error);
});
then() handles success, and .catch() handles any errors. Simple, right?
Step 3: Mini Project β Show a Dog Image in the Browserβ
<button id="getDog">πΎ Get Dog Photo</button>
<img id="dogPhoto" width="300" />
const button = document.getElementById("getDog");
const photo = document.getElementById("dogPhoto");
button.addEventListener("click", () => {
fetch("https://dog.ceo/api/breeds/image/random")
.then(res => res.json())
.then(data => {
photo.src = data.message;
})
.catch(err => {
photo.alt = "Could not load dog photo π’";
console.error(err);
});
});
Step 4: Recap β What Did We Learn?β
- What a JavaScript Promise is
- How .then() chains after a Promise resolves
- How .catch() handles any errors
- Built a fun app using an API with fetch