Skip to main content

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!


πŸ”Ή 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