Is it possible to determine the success or failure of an asynchronous function when the function itself already handles errors?

The architecture of my app is currently set up with functions that are scoped to specific modules, such as "Auth" for instance:

async function authenticate(email) {
    let authenticated = false;
    try {
      if (email) {
        if (!validEmail(email)) {
          console.error('Invalid email');
        } else {
          await APIAuthenticate(email);
          authenticated = true;
        }
      }
    } catch (error) {
      console.error(error)
    }
    return authenticated;
  }

One inconvenience I face is the need for the authenticated variable. It's necessary because I want to use the authenticate function in a separate view file to redirect the user once authentication is successful without directly handling routing logic within authenticate.

Currently, I have to manually track the authenticated status like this:

// MyView.js
const isLoggedIn = await authenticate("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b5a9aba386a3aba7afaae8a5a9ab">[email protected]</a>");
if (isLoggedIn) {
  router.push("/dashboard")
}

While the current setup works, I'm wondering if there is a better solution that doesn't require me to manually manage the authenticated status within the authenticate() function?

Answer №1

Uncertain about your question, but in the authenticate() function, you don't actually need to use success. You can handle it using throw and catch.

async function authenticate(email) {
    try {
      if (email) {
        if (!validEmail(email)) {
          throw new Error('Invalid email');
        } else {
          await APIAuthenticate(email);
        }
      }
    } catch (error) {
      console.error(error)
      return false;
    }
    return true;
  }

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

Loading content dynamically into a div from an external or internal source can greatly enhance user experience on a website. By

As I work on my website, I am incorporating a div structure as shown below: <div class="container"> <div class="one-third column"> <a id="tab1" href="inc/tab1.html"><h2>tab1</h2></a> </div> & ...

The ng-route feature seems to be malfunctioning and I am unable to identify the error, as no information is being displayed in the console

Here is the code in my boot.php file where I have set up the links <ul class="nav nav-pills nav-stacked"> <li role="presentation"><a href="#/valley">Valley</a></li> <li role="presentation"><a href="#/beach"> ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

Generate JSON on-the-fly with ever-changing keys and values

I am new to coding and I'm attempting to generate JSON data from extracting information from HTML input fields. Can anyone guide me on how to create and access JSON data in the format shown below? { Brazilians**{ John**{ old: 18 } ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

What is the most effective way to extract information from a .txt file and showcase a random line of it using HTML?

As a newbie in HTML, my knowledge is limited to finding a solution in C#. I am attempting to extract each line from a .txt file so that I can randomly display them when a button is clicked. Instead of using a typical submit button, I plan to create a custo ...

ng-table Filtering with dropdown selection

Hello, I am currently working on creating a Ng-table with a select dropdown menu for filtering the results. Here is where I am at so far. 1) How can I remove one of the pagination options that appear after applying the filter? I only want to keep one pagi ...

Ways to ensure the axios call is completed before proceeding with the codeexecution

I need to use axios to send a request and retrieve some data that I want to pass as a prop to a React Component. Here's my render function: render() { boards = this.fetchBoardList(); return ( <div className="app-wrapper"> ...

Utilizing ProtractorJS to Extract Numbers from Text within an Element and Dynamically Adding it to an Xpath Expression

Situation My objective is to extract text from an element on a webpage, convert that extracted text into a number in string format, and then use it for an xpath query. The code snippet below illustrates this process: var bookingRefString = element(by.css ...

What could be causing my jQuery switch not to function on the second page of a table in my Laravel project?

Having an issue with a button that is supposed to change the status value of a db column. It seems to only work for the first 10 rows in the table and stops functioning on the 2nd page. I'm new and could really use some help with this. Here's the ...

Customize dynamically loaded data via AJAX

I have a webpage that is loading a table from another source. The CSS is working fine, but I am facing an issue editing the table using jQuery when it's loaded dynamically through a script. It seems like my changes are not getting applied because they ...

VueJS - Harnessing the power of the Document Object Model for dynamic template rendering

Essentially, I am in need of VueJS to provide warnings for unregistered components when in DOM template parsing mode. It seems that currently Vue does not pay attention to custom HTML when using DOM templates, although errors are correctly displayed with s ...

Identifying Elements Generated on-the-fly in JavaScript

Currently, I am tackling the challenge of creating a box that can expand and collapse using regular JavaScript (without relying on jQuery). My main roadblock lies in figuring out how to effectively detect dynamically added elements or classes to elements a ...

Click twice on the editable AngularJS table to wrap each item

As a new learner of Angularjs, I found an existing code example and decided to customize it. My goal was to enable double-click editing for each li item. However, after adding one more li, the functionality did not work as expected. <li ng-dblclick="st ...

What is the best way to implement vuelidate when dealing with an array of objects?

In my form questionnaire, I am looping through an array of objects. Each object has five properties, but only one property needs validation. The validation setup in the component looks like this: specificGifts: { $each: { passThrough: { ...

Exploring the TLS configuration for a Node.js FTP server project: ftp-srv package

I'm seeking to comprehend the accurate setup of TLS for my FTP project (typescript, nodejs) using this API: ftp-srv The documentation provided is quite basic. In one of the related github issues of the project, the author references his source code / ...

Learn the technique of initiating one action from within another with Next Redux

I'm looking to set up user authorization logic when the page loads. My initial plan is to first check if the token is stored in the cookies using the function checkUserToken. Depending on whether the token is present or not, I will then call another f ...

Guide on serializing an object containing a file attribute

I'm currently working on creating a small online catalog that showcases various housing projects and allows users to download related documents. The data structure I am using is fairly straightforward: each project has its own set of properties and a ...

Refreshing Dropotron Data with jQuery

I'm struggling to find a solution for refreshing the <ul> and <li> elements after the page has already loaded. My <li> element is updated with Ajax data, but despite using jQuery to manipulate the DOM, the changes are not reflected ...