When there is an infinite loop in the run block, the $http success callback in the factory is not triggered

Take a look at my code with the relevant parts highlighted:

authorization.js

while loop is omitted, I encounter this error:

Cannot read property 'toString' of undefined

This error stems from attempting to call toString on currentUser._id while it's still undefined. My belief is that initially, Auth.getCurrentUser() returns a reference to {}. Upon assignment, {} should be assigned to currentUser, allowing the code to continue. However, since the response hasn't arrived yet, currentUser cannot be updated. Therefore, I resorted to using the while loop to halt execution until the response arrives. Surprisingly, the loop runs endlessly! Shouldn't the response eventually arrive, update currentUser, and turn !currentUser._id into false, breaking the loop?

Initially, factory cb and then userId get logged. Yet, the infinite loop kicks in without ever reaching

success</code/>. Doesn't asynchronous behavior dictate otherwise? How does the loop manage to interfere with the request completion? What exactly is happening here?</p>

<p>The call itself isn't causing issues; sans the <code>while
loop, the success callback gets triggered and logs success. Furthermore, upon console.dir(currentUser) in authorization.js, the user's info is displayed. Strangely though, using console.log(currentUser) yields an empty object. The reason behind this remains unclear.

Answer №1

From what I understand, due to Javascript being single-threaded, the http callback may not have access to CPU time to handle the response while the thread is stuck in the while loop.

Answer №2

It seems like the issue here is that your authentication processes are being checked asynchronously, which is likely due to the HTTP call required for validation.

At the moment when the script runs, the currentUser object from Auth.getCurrentUser() is not yet filled with the necessary data because it is being assigned at a later point in an asynchronous block:

angular.copy(data, currentUser);

As a result, it's possible that the property _id has not been added to currentUser yet, leading to the function toString() being called on undefined.

To address this issue, you may want to consider using callbacks or promises. If you have control over the auth.factory.js file, instead of returning the object synchronously in getCurrentUser, you could return a promise or callback that resolves once the HTTP request is complete.

Additionally, it's worth noting that the console.dir in your script may not display any data as it runs before the object is fully populated.

Answer №3

In Angular, services act as singletons which means they are created only once when needed and then the same instance is passed around as a dependency. This ensures that the code to fetch the current user is executed just once. However, if the user is not logged in, nothing will happen.

To handle this scenario using cookies, you can check if the user data is stored in the cookie before proceeding with your code to get the current user. If the current user is null, it indicates that the user is not logged in and you need to query the API for the data. In such cases, you should execute the code inside a promise.

Since the logic for handling both scenarios (user logged in / not logged in) is the same, it is recommended to move this code into a service for reusability.

Additionally, it is advisable to broadcast events each time the user logs in or out. This allows different parts of the application to listen to these events and react accordingly based on the information received.

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

jQuery and Ajax are facing a challenge in replacing HTML

Imagine a scenario where there is a button on a website that, when clicked, replaces a paragraph (<p>) with a header (<h1>). Unfortunately, the code to make this functionality work seems to be faulty: index.html <head> <script s ...

What are the best methods for testing REST API and Client-side MVC applications?

When dealing with a RESTful server that only responds with JSON data fetched from a database, and having a client-side application like Backbone, Ember or Angular, where should application testing take place? Is it necessary to have two sets of tests - on ...

React element failing to appear on webpage

I'm having trouble loading the snippetInfo.js file in the HTML, and I can't seem to figure out why. I've searched online extensively for solutions, but none of them have worked for me. Whenever I try adding type='text/javascript' t ...

Transferring data only once specific agreements have been fulfilled

Imagine having a file with specific promises that, when executed sequentially, create an input file called input.txt. // prepareInput.js var step1 = function() { var promise = new Promise(function(resolve, reject) { ... }); return p ...

Understanding the role of $element and $attrs in component controllers within AngularJS components version 1.5

Currently, I am in the process of familiarizing myself with 1.5 angular components. To kickstart my learning, I have been watching Todd Motto's videos and also referring to Angular's official documentation here. It appears that components are re ...

Bypassing angular's dependency injection by utilizing a universal object

Recently, I came across some code that utilizes a global object to store angular services. These services are attached to the global object within the run function of the angular module. It made me wonder, could this approach potentially lead to issues i ...

Async await function two is failing to execute

I am currently working on a process where I need to unzip a file first, wait for the unzipping process to complete, and then loop through each extracted file to upload it to an S3 bucket. The unzipPromise function is working as expected, successfully unz ...

JavaScript checking the current page's URL is crucial for maintaining accurate and dynamic

I've attempted to verify the URL using this specific function. It functions properly with single text, but fails when a URL is inputted. jQuery(document).ready ( function () { //var regExp = /franky/g; //It works fine ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

Is there a way to change the background color of a redirected page by clicking on a tag?

I have a specific goal in mind: when clicking on an anchor tag, it should redirect to page2.html and change the background color of a particular div on that page. (The anchor tag contains a URL and an ID in its href to direct to a specific section.) pa ...

View setup in progress

I'm interested in implementing something along these lines: app.config(function($routeProvider){ $routeProvider.when('products/list', { controller: 'ProductListCtrl', templateUrl : 'products/list/view.html', ...

Running a jQuery function that triggers a PHP script when the page

Hi there! I'm currently working on implementing jQuery's ajax feature to call a php script when the page loads. This php script will fetch xml data from a web service URL, parse it, and then display specific parts of it within a div tag on the pa ...

What purpose does the by.js locator serve in Protractor/WebDriverJS?

Recently, I've come across a new feature in the Protractor documentation - the by.js(): This feature allows you to locate elements by evaluating a JavaScript expression, which can be either a function or a string. While I understand how this locat ...

There was an issue attempting to access the 'host' property as it was undefined

I am facing an issue while trying to establish a connection between my application and MongoDB. The error message 'Error: Cannot read properties of undefined (reading 'host')' keeps popping up, and I'm unable to pinpoint the root c ...

Ways to update a div containing running php code

A set of images are displayed in a div with an option to rotate them if needed. Although the images rotate, they do not immediately appear on the page without manually refreshing it 2 or 3 times. I have included <meta HTTP-EQUIV="Pragma" content="n ...

Exploring the next() function in the Next JS API: A practical guide similar to Express JS

When creating an API in Next JS, I encountered an issue while passing three parameters to my API function (req, res, next). Take a look at the code snippet below: import catchAsyncErrors from "../../../middleware/catchAsyncErrors.js"; import conn ...

What is the best way to store the data in the lowest common ancestor for effective communication among multiple identical components within a sibling network?

My Background: I have expertise in Python and Vue development, with a history of using Vue dating back to 2016. One of my clients operates a business focused on weight loss and meal planning: clients pay her for weekly single-page PDF menus that outline t ...

How long do variables persist in a Factory in Angular JS?

Can anyone clarify the lifespan of variables stored in factory/services in Angular JS? Do the values persist after refreshing the page, or do they get reset? And what happens if we refresh the entire application? I am currently storing values in a factor ...

Is there a way to retrieve the ContentType of an ajax request using vanilla JavaScript?

I am currently working on a script that utilizes AJAX to make requests to a server. When the response is plain text, it gets placed in a div element. However, if the response comes back as JSON data, then it needs to be handled differently. var xhttp = ne ...

The display of the key property is missing on the rendered page in a React TypeScript project

While working with Typescript React, I encountered an error message: react-jsx-dev-runtime.development.js:87 Warning: Each child in a list should have a unique "key" prop. Even though I included a key in the li tag like this: const MyMenuItem: ...