Today, I need help on learning the concept of a JavaScript promise. Although I didn’t fully grasp it just yet, I realized I needed to implement a promise in my app to ensure my code could execute asynchronously, rather than having to wait for the completion of certain tasks. It was a bit daunting at first, but I discovered a nice video on YouTube that explained the concept very clearly. While I still have some gaps in my understanding, I’m optimistic and committed to practicing more until I get the hang of it.

Previously, I used to rely on the setTimeout() function to synchronize parts of my code. However, with the introduction of promises and the async and await keywords in JavaScript, I no longer have to worry about coordinating the execution order of my code blocks manually. These features make asynchronous programming so much more intuitive and effective, and I’m excited to incorporate them into my projects.

Below is the code I’ve written, inspired by the example provided in the video. It’s my first attempt, and I’m eager to refine it further as I continue to learn:

This version expands on your thoughts and adds structure, making the message flow more naturally while maintaining a conversational tone. Let me know what you think! 😊

In this example, the walkDog() has 5 secods, and the takeOutTrash() has two seconds, you would think that the takeOutTrash() would complete first, but no, the code waits for the walkDog() to complete the takeOutTrash().

      function walkDog() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            const dogWalked = true;
            if (dogWalked) {
              resolve("Dog walked");
            } else {
              reject("Dog not walked");
            }
          }, 5000);
        });
      }
      function takeOutTrash() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            const trashOut = true;
            if (trashOut) {
              resolve("Trash is out");
            } else {
              reject("NOT trash out");
            }
          }, 2000);
        });
      }

      async function doChores() {
        try {
          const walkDogResults = await walkDog();
          console.log(`LINE 42 walkDogResults=`, walkDogResults);
          const takeOutTrashResults = await takeOutTrash();
          console.log(`LINE 45 takeOutTrashResults=`, takeOutTrashResults);
        } catch (err) {
          console.log(`LINE 28 err=`, err);
        }
      }
      doChores();