Another option to avoid using complicated else if chains

I'm facing a challenge with a function that returns a value known as user_id. It involves multiple conditions that need to be checked.

First condition: Verify the service variable

Second condition: If not found, retrieve user_id from local storage

Third condition: If still not found, get firebase_uid from local storage, then invoke the function findUserId(firebase_uid) to get the user_id

Fourth condition: If all else fails, obtain uid from Firebase and call findUserId(uid)

Below is the code snippet.

export class UserService {

  user_id : any;
  firebase_uid: any;
  id: any;

returnUser_id() {

    if(this.user_id) {

      return this.user_id
    }

    else {
      this.storageService.get('user_id').then(val =>{
        if(val) {
          this.user_id =val
          return this.user_id
        }

        else {
          this.storageService.get('firebase_uid').then(value =>{
            if(value) {
              this.firebase_uid = value

              this.findUserId(this.firebase_uid).subscribe(q =>{
                console.log(q)
                this.id = q;
                for(let i =0; i<this.id.length;i++) {
                  this.user_id = this.id[i].id

                  return this.user_id

                }


                this.storageService.set('user_id', this.user_id ).then(result => {
                  console.log('Data is saved');
                  }).catch(e => {
                  console.log("error: " + e);
                  });


              })

            }
            else { 
              this.afauth.authState.subscribe(user =>{
                if(user) {
                  this.firebase_uid = user.uid; 


                  this.storageService.set('firebase_uid', this.firebase_uid ).then(result => {
                    console.log('Data is saved');
                    }).catch(e => {
                    console.log("error: " + e);
                    });


                    this.findUserId(this.firebase_uid).subscribe(data =>{
                      this.id = data;

                      for(let i = 0 ;i<this.id.length; i++ ){
                        this.user_id = this.id[i].id
                        return this.user_id
                      }

                      this.storageService.set('user_id', this.user_id ).then(result => {
                        console.log('Data is saved');
                        }).catch(e => {
                        console.log("error: " + e);
                        });
                    })
                }
              })
            }


          }).catch(err =>{
            console.log(err)
          })
        }
      }).catch(err =>{
        console.log(err)
      })
    }

  }

}

Function for finding User ID

findUserId(uid): Observable<any> {
  return this.http.get<User[]>(this.user_url + 'users?filter[fields][id]=true&filter[where][firebase_uid]=' +uid )

}

This code snippet may appear convoluted and challenging to comprehend. Are there any alternatives to using conventional if-else statements?

I appreciate any insights in advance

Answer №1

In order to improve our code efficiency, we can identify repeatable code segments and extract them into reusable methods. By utilizing the async keywords, we can simplify our code further.

if(this.user_id)   
    return this.user_id;
else {
    let user_id = await this.storageService.get('user_id');
    if (user_id)  
        return user_id;
    else {
        let firebase_uid = await this.storageService.get('firebase_uid');
        if (firebase_uid) {
            await reusableFindUserId(firebase_uid);

            if (this.user_id)
                await setStorageService();
        }        
        else { 
            let user = await this.afauth.authState();
            if (user) {
                this.firebase_uid = user.uid;
                await reusableFindUserId(firebase_uid);

                if (this.user_id)
                    await setStorageService();
            }
        })
      }
    }
}    

Additionally, we can define the following reusable methods:

async reusableFindUserId(firebase_uid){
    this.id = await this.findUserId(firebase_uid);
    for(let i =0; i<this.id.length;i++) {
        this.user_id = this.id[i].id;
        return this.user_id;
    }
}

async setStorageService() {
    return await this.storageService.set('user_id', this.user_id );
}

Answer №2

Considering removing the else statement, as you already return within the if-block. If a return is executed, the remaining code will not run. Review the entire function to determine if any other else statements can be eliminated. Remember, if you return, an else is not necessary :)

Additionally, consider breaking some sections of the code into separate functions. This will result in a cleaner and more concise main function.

if(val) {
      this.user_id =val
      return this.user_id
    }
// The else is not needed...
else {
    ....
}

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

I seem to be encountering an issue while looping through an array of objects. Instead of retrieving all two elements, only one object is being returned. Can

Just a heads up, I'm new to coding so please bear with me. I'm attempting to run through the "diary" array and the function "howMany" is only showing 2 'Home' elements, although there are actually 4 'Home' elements in total i ...

"Trouble with Angular's http.get method failing to retrieve data from MySQL through Node

I am struggling to retrieve data from MySQL using Angular and Node.js. Despite trying, I am unable to make it work. When I check Postman using the link http://localhost:8080/locations, I can see the data. { "status": "200", "items": [ { "cit ...

angularJS transformRequest for a specified API call

Looking for a way to pass multipart/formdata through a $resource in Angular so I can post an image. I discovered a helpful solution on this Stack Overflow thread. However, the solution applies to all requests within my modules, and I only want it to apply ...

Checking a sequence using a list of strings

I have an array containing a list of IDs: var listId: string[] = []; var newId: boolean; for (let i in data.chunk) { listId.push(data.chunk[i].aliases[0]); } My objective is to compare a new ID with the entire list. If the new ID is found in the list ...

Guide to emphasizing a specific term within a string by utilizing coordinates in javascript

I am facing a challenge when trying to highlight multiple words within a sentence. Specifically, I have text data that looks like this: "The furnishing of Ci Suo 's home astonished the visitors: a home of 5 earthen and wooden structures, it has a sit ...

"Converting an HTML file to a Word file using PHP - a step-by-step

Help needed with converting an HTML file to MS Word using PHP code. Below is the code I am using: include("connection.php"); extract($_REQUEST); ob_start(); include("counties/$county_name/$file"); $html_content = ob_get_contents(); ob_end_clean(); header ...

"Customizing text input colors in Angular Material: A step-by-step guide

Welcome to my User Form: https://i.stack.imgur.com/7eLp9.jpg I'm facing an issue where the color of the input field is white, blending with the background color. I've been searching for how to change the color of the input field without any luc ...

What is the best way to showcase several items in a slide with Ionic 2?

I am a beginner with Ionic 2 and I am trying to display multiple products in a single slide. While I have successfully displayed the slide, I am seeing small dots below the image. How can I remove these dots? Below is my HTML code: <ion-row class="bran ...

Efficiently reducing the size of a CSS selector string with javascript

Is there a library that already performs this function? I've only been able to find online tools. The reason I am interested in accomplishing this task using JavaScript is because I need to ensure that the strings a > b, a and a> b,a are conside ...

After diligently following every step on OneCheckout and getting no response when placing an order, I decided to upgrade my Magento version from 1.6.1.0 to 1.8

After upgrading the Magento version from 1.6.1.0 to 1.8.0, everything seems to be working smoothly. However, customers are facing an issue during checkout where they can't actually place their order. Despite following all the steps correctly, when t ...

Tips for importing "~bootstrap/scss/bootstrap" in a .html or .ts file while utilizing a carousel

I am looking to include the bootstrap carousel file in just one component, either a .ts or .html file. I do not want to have bootstrap integrated into the entire project via angular.json. Is it possible to import it into only one specific component? Does ...

Exploring nested JSON data in Vue.js

In my attempt to access nested JSON within an array using Vue for a simple search functionality, I encountered a problem. Each school is encapsulated in a "hit" array, causing the system to perceive only one result of "hit" instead of returning data for ea ...

Preventing the submission of a form using jQuery until all input, radio, select, and checkbox fields are filled out

I currently have a form that includes various field types, all of which must be filled out before submission. The submit button is disabled by default and I am looking to enable it once all fields are completed. I came across examples of this feature work ...

Angular dynamic data internationalization

Incorporating internationalization [i18n] into my angular project has been successful for static content, but I am encountering challenges with dynamic content. Below is a snippet of my code: Static: <div>{{ 'ADD ENTRY' | translate }} &l ...

Unlock the Power of Rendering MUI Components in ReactJS Using a For Loop

Hey there! Hope everything is going well. I've been working on a fun project creating an Advent/Chocolate Box Calendar using ReactJS. One challenge I'm facing is figuring out how to iterate over a for loop for each day in December and render it ...

Exploring Best Practices for Coding in node.js

Method 1: Constructor and Prototype Objects function Database(url) { this.url = url; } Database.prototype.info = function (callback) { http.get(this.url + '/info', callback); }; Method 2: Closures Approach function Database(url) { ...

Building a dynamic hierarchical list in Angular 8 with recursive expansion and collapse functionality

I am attempting to construct a hierarchical expand/collapse list that illustrates a parent-child relationship. Initially, the parent nodes will be displayed. If they have children, a carat icon is shown; otherwise, a bullet icon appears. When the carat ico ...

The dojo array implemented a new element, pushing out the old one

The JavaScript code below is supposed to populate the array personNames with objects containing names from an array of persons. However, it incorrectly repeats the same name for each object instead of assigning different names: [{"name":"smith"},{"name":" ...

Deploy the Angular standalone component numerous times across a single page using Bootstrap

Edit After receiving input from Andrew, I have decided to adjust my strategy: Replacing survey-angular with the survey-angular-ui package Implementing a widget approach similar to the one outlined in this example Developing a single module that encompass ...

When attempting to access index.html, the Express Server responds with a "Page Not Found"

I have encountered a problem while trying to run my Index.html file through an Express server. Despite referring to previously asked questions, I couldn't resolve the issue. The error message 'Cannot GET /' keeps popping up. Below is the sn ...