When a JavaScript program encounters an error, the Try Catch statement will log the errors in the

This particular code snippet is designed to loop indefinitely until the user enters the correct answer in a prompt. The acceptable answers are "left" and "right". If the user inputs any other text, the function promptDirection will throw an error and execute the catch block, prompting the for loop to restart.

One thing that perplexes me about this code is why errors like "Not a valid direction. Try again." are not showing up in the console log each time the catch block runs. These errors only appear once the user provides the correct answer or clicks cancel in the prompt, resulting in a return of "null" which ends the program.

Can anyone shed some light on this behavior?

I would anticipate seeing an error displayed in the console every time the user inputs something other than "left" or "right" into the prompt. However, in practice, if the user enters three incorrect answers, the errors only show up after the program finishes running, displaying three instances of "Not a valid direction. Try again." along with "You chose L" or "You chose R."

For example, inputting into the prompt:

Wrong

Wrong

Wrong

Left

The console does not show any indication of the catch block being triggered three times by InputErrors ("Not a valid direction") until the correct answer is entered. All accumulated errors become visible in the browser console once the program concludes and the correct Left answer is provided.

class InputError extends Error { }
function promptDirection(question) {
  let result = prompt(question);
  if (result.toLowerCase() == "left") return "L";
  if (result.toLowerCase() == "right") return "R";
  throw new InputError("Invalid direction: " + result);
}

for (;;) {
  try {
    let dir = promptDirection("Where?");
    console.log("You chose ", dir);
    break;
  } catch (e) {
    if (e instanceof InputError) {
      console.log("Not a valid direction. Try again.");
    } else {
      throw e;
    }
  }
}

Answer №1

To resolve the issue, consider implementing a solution using the setTimeout method.

class InputError extends Error {}

// original function definition
function promptDirection(question) {
  let result = prompt(question);
  if (result.toLowerCase() == "left") return "L";
  if (result.toLowerCase() == "right") return "R";
  throw new InputError("Invalid direction: " + result);
}

// async function wrapper to enable use of await
(async() => {
  for (;;) {
    try {
      let dir = await wait(() => promptDirection("Where?"));
      console.log("You chose ", dir);
      break;
    } catch (e) {
      if (e instanceof InputError) {
        console.log("Not a valid direction. Try again.");
      } else {
        throw e;
      }
    }
  }
})()

// utilizing setTimeout to call a function asynchronously
async function wait(fn) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        resolve(fn())
      } catch (e) {
        reject(e)
      }
    })
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Output PHP variable in JavaScript (and show the value within an iframe)

I'm trying to retrieve a value from a MySQL database using PHP, store it in a variable, output the PHP variable in JavaScript, and then display the value in an iframe. However, I'm having some trouble getting it to work... Here is my PHP code: ...

Leverage WooCommerce API in conjunction with Express.js

Here's the code snippet I've been working on: const express = require('express'); const router = express.Router(); const WooCommerceAPI = require('woocommerce-api'); const WooCommerce = new WooCommerceAPI({ ...

What do you believe to be superior: Vue UI design?

Scenario: Application managing multiple user roles. A view with extensive conditional rendering in the template. a) Is it preferable to have numerous conditional statements in a single view's template? b) Should separate views be created for each ro ...

Using the -g flag in Node.js consistently results in error messages

Whenever I attempt to install something globally with node, I encounter a series of errors. Interestingly, when I tried it in Powershell, no errors were thrown, but I suspect this is due to the fact that I was using Powershell instead of the official Node ...

What could be causing the issue with HTML not being printed upon button click in ReactJS?

My goal is to display the word "Hello" on the screen when the add button is clicked. However, I am encountering an issue where it is not showing up. Any insights or solutions would be greatly appreciated! import React, { Component } from 'react'; ...

Looking to implement a star rating feature in Vue.js 2?

My perspective is as follows : <div class="col-md-8"> ... <star-rating :value="3"></star-rating> ... </div> This is how my star-rating component looks like : <template> <span class="rating"> &l ...

How can we effectively implement an auto login feature using JWT?

Having recently delved into jwt authorization, I find myself transitioning from traditional user and password authorization to a more secure method. After grasping the fundamentals of jwt, I am eager to implement it in my workflow and have a question: Upo ...

Adding unique parameters to a rails form

As a newcomer to web development, I am facing the following challenge: I have three models in my application: products class Product < ApplicationRecord has_and_belongs_to_many :steps end steps class Step < ApplicationRecord has_and_belongs_ ...

Executing asynchronous functions synchronously

I am relatively new to JavaScript programming and I am currently trying to grasp the concepts of asynchronous processes. In my project, I am looking to execute the following code synchronously. Despite watching numerous tutorials on the subject, I find mos ...

Learn how to synchronize input field with a checkbox using v-model and computed property in Vue.js

Trying to find the best way to mirror two input fields and update them dynamically based on a checkbox value. Currently, I am using computed properties with get and set features. The issue arises when the user enters "ABC" in shipping details, unchecks the ...

Confirming the Checkbox Field - ASP.NET with the Power of jQuery

I am currently working on a straightforward validation process for checking agreements using an asp:checkbox and an asp:button click. When the button is clicked, I have this function being called: OnClientClick="ValidateConditions();" The function itsel ...

I am attempting to retrieve the bot's permissions in order to validate if the command is authorized to execute

To verify if a command can be executed, I am attempting to retrieve the bot's permissions. Here is the code snippet I am using: let botid = "idbot" let bot = client.users.cache.get(botid) if (!bot.permissions.has("ADMINISTRATOR")) ...

Utilizing AngularJS to Implement Gradient Effects Using the ng-style Directive

Having trouble setting gradients using the angular js ng-style directive. I can successfully set normal colors using the code below: <span ng-style="{'background-color': slidercolor}">works</span> However, when trying to set a gradi ...

Extract information from various files stored in Firestore

I have been struggling to retrieve data from multiple documents despite numerous attempts. The screenshot below displays that I have a collection of 3 documents, and my inquiry is how to extract data from each of them. https://i.stack.imgur.com/bFrIG.png ...

Facing Issues with User.update in Mongoose and MongoDB

I have been struggling to create a new collection and push it into a specific user's collections array. Despite researching various stackoverflow posts, I am unable to achieve this using either User.update() or User.findOneAndUpdate(). I can confirm t ...

Navigation menu with submenus containing buttons

I attempted to incorporate a dropdown into my existing navigation bar, but unfortunately, the dropdown content disappeared after adding the necessary code. I am now at a loss on how to troubleshoot this issue and make the dropdown function properly. Despit ...

Tips for creating a unique exception in AngularJS?

I have a customException.js script with the following service: app.service('CustomException', function() { this.CustomException1 = function (message) { if (!message) { message = "Custom Exception 1 occurred!"; } return { ...

Can two different versions of ReactJS run simultaneously on a single page?

Hey everyone, I'm curious if it's possible to have two different versions of ReactJS running on the same page, similar to how jQuery has jQuery.noConflict(). After doing some research, I came across some interesting findings: Two Reacts Won’t B ...

When I click on the button, the page reloads instead of executing the essential code

On my website, there is a settings page where users can edit their profiles. After editing, they click the update button which triggers the updateProfileData function. This works smoothly in Chrome browser, but in Firefox, the page reloads as soon as the b ...

How to upload an Image to Cloudinary using Express.js, React, and Axios for a POST

I encountered an issue while attempting to upload images to Cloudinary using a React front-end and Express server. The problem lies in not being able to properly post request the image to my Express server. Here is how I prepare the image for sending it l ...