skip to Main Content

The problem with the code is that I inputted everything right and nothing is showing up. Code for reference:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>order</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>

  <div id="demo"></div>

  <script>
    let tag = document.getElementById("demo");

    function display(value) {
      tag.innerHTML = value;
    }

    let toldThePeople = "BBQ Cauliflower";

    // Restaurant order 
    let restaurantOrder = new Promise(function (resolve, reject) {
      let order = "BBQ Corn";

      if (toldThePeople === order) {
        resolve("Mmm, You guys did an awesome job!");
      } else {
        reject("I WANT THE MANAGER!!!");
      }
    });

    restaurantOrder.then(function (value) {
      display(value);
    });
  </script>
</body>

</html>

As shown there is a promise which should work but isnt.


I tried to play the code and it would not show up. Is there any wrong reference? Is the html code wrong?

2

Answers


  1. That’s because the reject of the promise is being called which doesn’t enter then but instead causes the catch to be called:

    restaurantOrder.then((value) => {
      display(value); // when resolve is called
    }).catch((value) => {
      display(value); // when reject is called
    });
    
    Login or Signup to reply.
  2. as I see promise is working fine. I think you are expecting the reject(promise) value in .then function. When the promise get reject then catch block code execute. You need to add catch block for reject case of promise as mentioned below

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>order</title>
      <link href="style.css" rel="stylesheet" type="text/css" />
    </head>
    
    <body>
    
      <div id="demo"></div>
    
      <script>
        let tag = document.getElementById("demo");
    
        function display(value) {
          tag.innerHTML = value;
        }
    
        let toldThePeople = "BBQ Cauliflower";
    
        // Restaurant order 
        let restaurantOrder = new Promise(function (resolve, reject) {
          let order = "BBQ Corn";
    
          if (toldThePeople === order) {
            resolve("Mmm, You guys did an awesome job!");
          } else {
            reject("I WANT THE MANAGER!!!");
          }
        });
    
        restaurantOrder.then(function (value) {
          display(value);
        }).catch((value)=>{
            display(value);
        });
      </script>
    </body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search