Angular promise did not assign a value to a variable

Can someone assist me with a problem I'm facing? After the first callback, the variable doesn't seem to change as expected. Below is my code snippet:

    this.handlerLocalDef = function(defer) {
        var hash = {};

        defer.then(
               function(response) {
                   hash = response;
               },
               function(err) {
                   showPopup(err);
               }
        );

        return hash;
    };

    var initialized = function()  {
        var localRegDef = Localization.getLocalizedDefer('regularform'),
            localPaymDef = Localization.getLocalizedDefer('payment');

            localizeRegForm = self.handlerLocalDef(localRegDef);

            $timeout(function() {
                console.log("localizeRegForm", localizeRegForm);
            }, 5000);
   }();  

Upon checking the console log, it shows `localizeRegForm: {}`

Answer №1

Simply assigning hash = response only changes the reference of the local variable, not the original object itself. To properly update the original object with the values from response, you can use angular.extend(hash,response);. This will effectively copy all members of response into the hash object, ensuring that the receiver sees these changes.

Note: Be aware that this method may not work for primitive values (strings, numbers, booleans, etc.) or arrays.


Here is a fiddle showcasing the suggested approach: http://jsfiddle.net/sVRCg/3/


If you have concerns about how to verify that hash has been extended with response, using polling like setTimeout is not ideal. Consider returning a promise instead to accurately track when the response is ready.

Alternatively, explore implementations similar to how ngResource handles this process, although it may involve more complexity in the code structure.

Answer №2

Async programming should not involve setting arbitrary timeouts and hoping for data at a specific point in time. It's important to use deferred objects as intended and utilize callbacks for more reliable functionality. Here is a suggestion on how you can restructure your code to ensure it works properly, although effectiveness may vary based on your unique circumstances:


    this.handlerLocalDef = function(defer,callback) {

        defer.then(
               function(response) {
                   callback.apply(this,[response])
               },

               function(err) {
                   showPopup(err);
               }
        );

    };



    var initialized = function()  {
        var localRegDef = Localization.getLocalizedDefer('regularform'),
            localPaymDef = Localization.getLocalizedDefer('payment');


            self.handlerLocalDef(localRegDef,function(response) {
                console.log(response);
            });
   }(); 

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

Transforming the NavBar in React: A guide to dynamically updating values

I am facing an issue with my NavBar that changes based on certain events. The current setup works fine, but I don't want to render it in every class that loads a new page. Initially, I had the NavBar rendering inside App.js so it could appear on all p ...

Django Vue3 encounters access-control-allow-origin restriction

I am currently working on a Django rest-api project that uses Vue on the front-end. Unfortunately, I encountered an error while making requests via Vue: Console output: The following error is displayed: Access to XMLHttpRequest at 'https://api.iyziw ...

How can I ensure that the size of the Dropdown Menu Item matches its parent in both Bootstrap and CSS styles?

I am working on a navigation bar that has a dropdown menu which appears on hover. I want the size of the dropdown menu items to match the size of the parent element. Here is an image for reference: https://i.stack.imgur.com/oNGmZ.png Currently, the "One ...

Using Bootstrap multiselect, you can easily control the display of a second menu based on the selection in the first menu

On my website, I am working with two menus. When I select Abon from the first menu, it should display all li elements under the Abon optgroup (Abon-1, Abon-2). If I uncheck block in the second menu, those elements should disappear. The code consists of Sel ...

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

Can the autocomplete feature be utilized in an input field without incorporating a map?

I am struggling with a search field that does not utilize the map functionality. html <input type="text" ui-gmap-search-box ng-model="GeneralFactory.Location" events="searchbox.events" placeholder="Location" class="form-control input-lg"> app.js ...

Ways to monitor the status of a server request using jQuery (ajax)?

I am currently working on a PHP application that involves users submitting forms to the server via ajax (jQuery). The server needs to insert a large number of records into a MySQL database, which may take some time due to various calculations. My question ...

Tips for implementing an automated date picker in Selenium using Node.js

I attempted to automate a date picker like the one shown in this screenshot: Below is the code I used to automate it using Selenium with NodeJS: const { By, Key, Builder, WebElement, Alert } = require('selenium-webdriver'); require('chro ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

When using Material UI, I ran into an issue where my Card Component was being added to my Appbar. To improve user interaction, I desire for the cards to only appear once

The formatting of the naming conventions is incorrect. Please disregard those. Snippet of code for the Appbar: const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1 }, title: { flexGrow: 1 } })); export default function Appp() ...

Divide a given number of elements within an array of arrays

Presented below is an array: [ { "id": "34285952", "labs": [ { "id": "13399-17", "location": "Gambia", "edge": ["5062-4058-8562-294 ...

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

The issue of underscorejs being undefined arises when trying to load it using both XMLHttpRequest and

I am attempting to dynamically load underscorejs using XMLHttpRequest and eval function function includeScriptSync(scriptUrl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", scriptUrl, false); xmlhttp.onreadystatechange = function() ...

Please be patient until setInterval() completes its task

In order to add a dice-rolling effect to my Javascript code, I am considering using the setInterval() method. To test this out, I have come up with the following code: function rollDice() { var i = Math.floor((Math.random() * 25) + 5); var j = i; ...

Refreshing html in nodejs after a fetch promise remains in a pending state

I am facing an issue with the `then` method in Express and Node.js as it is logging a promise that remains pending. edit().then(data => console.log(data)); Below is the code for the edit function: async function edit(data, id) { let response = aw ...

How to create a vertically scrollable div within another div by utilizing scrollTop in jQuery

I need assistance with scrolling the #container div inside the .bloc_1_medias div. The height of #container is greater than that of .bloc_1_medias. My goal is to implement a function where clicking on the "next" and "previous" text will scroll the #contai ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Looking for an uncomplicated SSO system similar to Google Identity Toolkit but with a customizable UI interface?

I'm really impressed with the Google Identity Toolkit, it's so user-friendly and easy to set up! However, I'm having trouble with the fact that it forces me to use its UI. Is there another option available that will allow visitors to simply ...

Limitation on calling $http.get() multiple times is in place

Complete Rewriting Of Inquiry The situation has taken a new turn, prompting me to clarify the current scenario from scratch. My goal is to develop a straightforward message board using Node, Express, MongoDB, and Angular. On the server side, my get and ...