Ilja
Ilja

Reputation: 46479

Knowing if async function succeeded or failed when that function already catches error?

I have structure of my app set up where I use functions like this, that are scoped to "Auth" for example:

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

As you can see there is one inconvenience there with success variable, it is there because I need to use authenticate function inside another view file to reroute user once authentication is successful (I don't want to reroute user within authenticate function itself in order to keep them as separate concerns and not import routing logic into auth).

At the moment I use it like so

// MyView.js
const success await authenticate("[email protected]");
if (success) {
  router.push("/dashboard")
}

In general it works, but I wanted to ask if there is a solution that won't require me manually tracking success variable inside authenticate() function?

Upvotes: 0

Views: 29

Answers (1)

William Chong
William Chong

Reputation: 2203

Not sure what exactly do you mean, but the success is actually not needed in authenticate(). Just handle it with 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;
  }

Upvotes: 1

Related Questions