Commitment and the worth of pointing

I am trying to create a promise chain in Angular to execute a series of queries:

           for(variableIndex in _editableVariable.values) {
                var v = _editableVariable.values[variableIndex];
                if(v.value != v.old_value) {
                    console.log('v', v);
                    var newVariableRes = new VariableValueRes(v);
                    if(v.old_value == undefined) {
                        p.then(function() {
                            console.log('B', newVariableRes);
                            return newVariableRes.$save().$promise;
                        });
                    } else {
                        console.log('Try update: ', v);
                        p.then(function() {
                            console.log('C', newVariableRes);
                            return newVariableRes.$update().$promise;
                        });
                    }
                }
            }

However, I am encountering an issue when I output the console.log('v',v), which shows different value for each variable. Inside the promise, when I output the console.log('B', newVariableRes), the content of newVariableRes is always the value of the latest variable.

Example Output:

v 
Object {value: "1", old_value: undefined, platform: "/api/v1/platform/1", product_variable: "/api/v1/product_var/2"}
v 
Object {value: "2", old_value: undefined, platform: "/api/v1/platform/2", product_variable: "/api/v1/product_var/2"}
v 
Object {value: "3", old_value: "", id: 7, platform: "/api/v1/platform/3", product_variable: "/api/v1/product_var/2"}

B 
Resource {value: "3", old_value: "", id: 7, platform: "/api/v1/platform/3", product_variable: "/api/v1/product_var/2"…}
B 
Resource {value: "3", old_value: "", id: 7, platform: "/api/v1/platform/3", product_variable: "/api/v1/product_var/2"…}
C 
Resource {value: "3", old_value: "", id: 7, platform: "/api/v1/platform/3", product_variable: "/api/v1/product_var/2"…}

I am new to JavaScript and I believed that v is a reference to the value. So, when I pass v to VariableValueRes, it should hold that reference. Changing the reference of

v</code should not affect the content of <code>VariableValueRes
.

Where could be the source of my misunderstanding?

Answer №1

One issue to consider is the scope in JavaScript, which is either global or function-based. This means that variables like v and newVariableRes declared within a for loop are treated as if they were declared at the top of the surrounding function.

During each iteration of the loop, the value of v is updated and logged immediately, reflecting the expected value. However, once the promise callbacks are executed, the loop has already completed, causing v and newVariableRes to hold the last assigned values.

These callbacks utilize newVariableRes through closure, allowing them to access the value from the outer scope even after the outer function has finished. This can lead to common mistakes in JavaScript code.

To resolve this issue, it is recommended to encapsulate the variable within a new function scope. One approach is to create a function and pass the variable as a parameter, ensuring that the callback uses the correct value:

p.then((function(nvr) {
    return function() {
        console.log('B', nvr);
        return nvr.$save().$promise;
    };
})(newVariableRes));

Alternatively, when using Angular, replacing the for loop with angular.forEach can also solve the problem by maintaining the expected value of v in the callbacks. This way, you can create new VariableValueRes(v) within the callbacks without worrying about the reference to newVariableRes.

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

Enhance your Vue.js 3 tables with sorting, filtering, and pagination capabilities using this custom component

After extensive research, I am still unable to find an updated Vue.js 3 component that offers sorting, filtering, and pagination for tables without the need for additional requests to a backend API. The options I have come across either seem outdated, are ...

Ways to initiate a transition upon clicking a button, causing it to switch from being hidden (`display: none`) to visible (`display: block`)

I'm attempting to create a smooth transition effect when a button is clicked, similar to a toggle function, where the content below it seamlessly shifts instead of abruptly moving. The classic example of this is the Bootstrap navbar hamburger menu, wh ...

What is the best way to extract the information from the checkbox in a MUI datatable?

I am struggling to transfer an array with checked values to another table in order to display only those values. How can I achieve this? I am relatively new to using react and I find it challenging to grasp how some of the functions and components work. I ...

Trouble mapping an array of objects in ReactJS

I'm encountering an issue where I am unable to map through an array of objects in my component. Although I have used this map method before, it doesn't seem to be working now. Can anyone help me figure out what's going wrong? import React, ...

Leverage the power of AJAX for searching in Laravel 5.3

This section contains views code related to form submission: {!! Form::open(['method'=>'GET','url'=>'blog','class'=>'navbar-form navbar-left','role'=>'search']) !! ...

What is the process for incorporating a custom attribute into an element with Vue directives?

One of the challenges I'm facing is dealing with a custom attribute called my-custom-attribute. This attribute contains the ID for the element that needs to have the attribute added or removed based on a boolean value. Although I've implemented ...

Error with encoding Uri segments in angular-resource.js

I'm facing an issue with querying restful resources that have multiple subpaths in their URI: For example: .factory('SomeFactory', function ($resource) { return $resource('/path/subPath/otherSubPath/:id', {}, { show: { method: &a ...

Error message: "Property undefined when Angular attempts to call a function from jQuery/JavaScript."

I'm currently attempting to invoke an angular controller from my JavaScript code. This is my first encounter with Angular and I must admit, I'm feeling a bit overwhelmed! I've been following this example: Unfortunately, when testing it out ...

What is the best way to save a multi-line text file - should it be stored as a regular text file or as a

I am currently developing a discord bot with discord.js and NodeJS. One of the challenges I am facing is sending a multi-line message (approximately 20 lines) to a specific channel for a particular command. In order to enhance the code's readability, ...

Integrate PHP include files into a website without allowing direct access, then dynamically load them using jQuery AJAX

I am utilizing jQuery AJAX to load the content of about.php page into my index.php section in this manner: $('.nav a[href="#about"]').on('click', function() { $('main').load('../../layout/about.php'); }); The iss ...

Attempting to modify the background hue of a Bootstrap 5 Button using javascript

I've been experimenting with changing the background color of a bootstrap 5 button using JavaScript. While I've been able to successfully change the text color with JavaScript, altering the button's color has proven to be elusive. Below is ...

Issue with Pop Up not redirecting correctly after a successful login in Azure AD

I recently integrated Azure AD with my web application. When clicking on the login window, a pop-up appears with the URL . It prompts for the Azure AD username and password. However, after successfully logging in, a code is returned as a parameter but the ...

Deactivate certain choices in React Select

Encountering difficulties disabling specific options in a large list within a React Select component. A total of 6,500 options are loaded into the select element. Initially, there were issues with search functionality lagging, but this was resolved by impl ...

Having trouble retrieving the variable from a newly created filter in an ng-repeat loop in AngularJS

Here is an example of my ng-repeat: <a class="item item-avatar" ng-click="loadProfile({{student.pi_id}})" ng-repeat="student in filteredStudents = (students | filter:model.txtSearch)" > <img src="./img/man.png"> <h2 ...

Encountering a build error with Ubuntu, Node-Gyp, and Canvas – help needed!

Hey there, I'm having some trouble with installing the Canvas package. I've tried Package Versions 6.1.13 and 6.1.3 Here are my system details: Ubuntu 18.04.5, Node 12.18.4 LTS, Python 2.7, g++ installed, pkg-config installed, libjpeg installed ...

In need of assistance with filtering lists using JQuery

Hi there! I'm looking to modify a list filtering function by targeting multiple ul tags within the same div instead of just filtering li elements. Any ideas on how this can be achieved? Below is my JavaScript code: $( document ).ready(function() { ...

Stop users from being able to select or highlight text within a content editable div

Is there a method to develop a content-editable div where users are unable to select or highlight content, but can still input information? I'm interested in creating an interface that forces users to delete and enter data character by character, with ...

When trying to use routes with the .map() function, it does not seem

I am currently working on developing a multi-page web application using react-router-dom. However, I have encountered an issue with the user list page (userlist.js) where the data inside the .map() function is not being returned. Interestingly, the code pr ...

Displaying empty values as zeros

Currently, I am creating a chart using Morris js. The data for the chart comes from a server and consists of dates and values. However, there are cases where certain dates do not exist in the data set. In such situations, I want to display these non-existe ...

Error detected in JSON syntax... Where is it hiding?

After running the code through jsonlint, it flagged an error on line 17. However, upon close inspection of the file which contains about 1000 lines, I couldn't pinpoint the issue. It's possible that the problem lies further down the file, but I w ...