Javascript skips the if-else block when used asynchronously

I'm struggling with an if-else block in my code that is not getting executed as expected. Despite rearranging the code to ensure the if-else condition is met before calling http.get(), I am still facing issues. This problem arises while working with AngularJS.

//controller
function search($scope, $http, $location) 
{
    function parse(item)
    {
      if(item.match(/str1/g))
      {
        item = item.replace(/str1/g, 'one');
      }

      else if(item.match(/str2/g))
      {
        item = item.replace(/str2/g, 'two');
      }

      else if(item.match(/str3/g))
      {
        item = item.replace(/str3/g, 'three');
      }

      //and so on
      return item;
    }

    $http.get('/search='+ parse($location.search().query.toLowerCase()))
         .success(function(data) {
            $scope.count = data.length;
            $scope.items = data;
            $scope.exists = data.length > 0;
         })
         .error(function(err) {

         });
}

Answer №1

Ensure that you include a return statement in your parse() function to return the processed item value. Without a return statement, the function is treated as a string and does not produce an output.

Add a return statement at the end of your parse() function like this:

function parse(item)
{
  if(item.match(/str1/g))
  {
    item = item.replace(/str1/g, 'one');
  }

  else if(item.match(/str2/g))
  {
    item = item.replace(/str2/g, 'two');
  }

  else if(item.match(/str3/g))
  {
    item = item.replace(/str3/g, 'three');
  }

  //and so on

  return item;

}

For more information on return statements, check out: http://www.w3schools.com/jsref/jsref_return.asp

An alternative approach is to handle the string manipulation directly within the search() function without creating a separate parse() function:

function search($scope, $http, $location) 
{
      var item = $location.search().query.toLowerCase();

      if(item.match(/str1/g))
      {
        item = item.replace(/str1/g, 'one');
      }

      else if(item.match(/str2/g))
      {
        item = item.replace(/str2/g, 'two');
      }

      else if(item.match(/str3/g))
      {
        item = item.replace(/str3/g, 'three');
      }

      //and so on

    $http.get('/search='+ item)
         .success(function(data) {
            $scope.count = data.length;
            $scope.items = data;
            $scope.exists = data.length > 0;
         })
         .error(function(err) {

         });
}

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

Using the Firefox API to determine if a tab is currently active

I remember hearing about a feature that was introduced in some recent versions of Firefox allowing developers to check if a tab is active or not using JavaScript. However, I am having trouble finding more information about it online. Can you share the li ...

Converting time from 00:00:01 to a format of 8 minutes and 49 seconds in Angular

Is there a way to transform a time value from 00:00:01 (not a date object) into a format showing 8 minutes and 49 seconds? Even after consulting the Angular 'date pipe' documentation, I couldn't find a solution to this issue. ...

Encountering an issue such as "Exceeding the maximum number of re-renders. React restricts the amount of renders to avoid

Currently, I am attempting to update the state within the request data method for a string variable as shown below: const ViewChangeRequest = () => { const [requestStageValue, setRequestStage] = useState(''); const { data: request ...

Utilizing JSON data as a variable for handling in a Handlebars view within a Node.js/Express application

I am currently seeking a solution to display a view that includes a variable with data fetched from an API. My technology stack involves express, handlebars, and request. Here is the code for the web server's router: const express = require('ex ...

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

AngularJS refresh the display of ngRepeat items

I'm currently displaying products and their details using ngRepeat in a table. In addition to that, I have created a custom directive: .directive('onFinishRenderFilters', function ($timeout) { return { restrict: 'A', ...

Is it possible for a function to alter the 'this' object in JavaScript?

Referencing the MDN article on this keyword in JavaScript When not in strict mode, 'this' in a function will point to the global object. However, attempting to modify a global variable within a function does not result as expected. Is there an ...

The JavaScript operator that functions in a manner akin to the SQL "like"

I am working on a jQuery function that needs to perform like the "like" operator. Can anyone help me achieve this? Your assistance is greatly appreciated. The function currently only works if I search for the whole word, for example: var vsearch = "home" ...

The variable 'props' is given a value but is never utilized - warning about unused variables in Vue 3

Within my Vue component file, I am using the following code: <template> <router-link :to="{ name: routerName }" type="is-primary" class="inline-flex justify-center py-2 px-3 mb-3 border border-transparent shado ...

Retrieving input values from forms

angular.module('app', []) .controller('mainCtrl', ['$scope', function ($scope) { $scope.checkVal = function () { console.log('entered'); console.log($scope.data.user) } ...

Tips for sharing data between React components without causing re-renders or relying on JSX, such as through a function within functional components

As a beginner in react, I have been struggling to find answers to this issue. I am trying to figure out how to pass data from one functional component to another in react without actually rendering the child component. Does anyone know a solution for this ...

"Utilize jQuery to load a file when hovering over a specific

How can I dynamically load an external file using jQuery when a user hovers over a specific div? I attempted to load the file like a CSS file on hover but was unsuccessful. Is it possible to load a CSS file on hover as I've seen in some examples? $(d ...

How does the 'this' variable function when it comes to models in embedded documents?

Being relatively new to node.js and sails, I find it quite easy to work with and enjoy it :) Currently, I am using the sails Framework version 0.10rc3 with MongoDB and sails-mongo. I understand that the contributors of waterline do not particularly like e ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...

Is there a way to escape from an iFrame but only for specific domains?

if (top.location != self.location) { top.location = self.location.href; } If my website is being displayed in an iFrame, this code will break out of it. But I want this to happen only for specific domains. How can I perform that check? ...

Does the react-google-login library utilize the services provided by Google Identity?

Currently incorporating the react-google-login library (https://www.npmjs.com/package/react-google-login/v/5.2.2) in my JavaScript codebase to grant users access to my website. Can anyone confirm whether this library utilizes "Google Identity Services" or ...

Is there a way to prevent javascript from automatically inserting tags when selecting text?

If you want to view the Fiddle Here Essentially, it's a text-highlighting tool that works almost flawlessly. The problem arises when it encounters tags like <p> or <br> within the selection. The JavaScript code seems to automatically in ...

Adding an active class to a large image when a thumbnail image is clicked can enhance user experience and

I've created a photo gallery using jquery. Currently, when I click on "next", the image changes based on the index. However, I also want to be able to click on the thumbnails (small images) and display the larger image according to that specific inde ...

How come my directive is being updated when there are changes in a different instance of the same directive?

For the purpose of enabling Angular binding to work, I developed a straightforward directive wrapper around the HTML file input. Below is the code for my directive: angular.module('myApp').directive('inputFile', InputFileDirective); f ...

What is the best way to transmit a 500x500 2D Integer Array using Websockets?

I'm encountering an issue where I believe it may be too time-consuming to JSON.stringify and send data to each individual user. For example, if 4 people connect at the same time, the server will become stalled during array parsing, resulting in signif ...