Attempting to transmit a dynamic array of promises from Angular to an Express server

Currently, I am attempting to send an array of promises to an express app in order to retrieve data from a mongo database. The behavior seems to be working fine on the front end. In this scenario, both objects are sent to the server and resolved using $q.all. However, during my debugging process on the server side, I noticed that both objects end up being the same. Specifically, it is the last promise with payload2 that gets resolved twice. Even when adding more promises, the correct number gets resolved but they all seem to be values from the last object in the array.

   var promises = logCspItemInventoryStatus(payload,result.cspItems);

    return $q.all(promises)
        .then(function(result){
          toastr.success('Items have been logged');
      })
       .catch(function(err){
         toastr.error(err);
       })

var logCspItemInventoryStatus = function (payload,cspItems) {
    var promises = [];
     angular.forEach(cspItems, function(item){
           //I am appending payload with items
           payload.qty=item.checking;
           payload.description=item.description;

           //payload 1 {docId: "55c124f7485684e81d6181fc", by: "Foo Bar", checkIn: false, qty: 2, description: "car"}
           //payload 2 {docId: "55c124f7485684e81d6181fc", by: "Foo2 Bar2", checkIn: false, qty: 1, description: "hall"}

           var p = checkOutCspItem(payload);
           promises.push(p);
    });

    return promises;
 };

//returns a promise
var checkOutData = function(payload) {
  return Csp.update(payload).$promise.then(function(result) {
    return result.data
   });
}

Answer №1

The issue arises from continuously modifying the payload parameter, which is an object and thus passed by reference. This means that every time it is altered, all references to it are affected, including those already included in the array of promises.

var promises = logCspItemInventoryStatus(payload,result.cspItems);

    return $q.all(promises)
    .then(function(result){
      toastr.success('Items have been logged');
    })
   .catch(function(err){
     toastr.error(err);
   })

var logCspItemInventoryStatus = function (payload,cspItems) {
var promises = [];
 angular.forEach(cspItems, function(item){
      //Appending items to a copy of payload
       var payloadCopy = angular.copy(payload);
       payloadCopy.qty=item.checking;
       payloadCopy.description=item.description;

      //Example of payloads: 
      //{docId: "55c124f7485684e81d6181fc", by: "Foo Bar", checkIn: false, qty: 2, description: "car"}
      //{docId: "55c124f7485684e81d6181fc", by: "Foo2 Bar2", checkIn: false, qty: 1, description: "hall"}

       var p = checkOutCspItem(payloadCopy);
      promises.push(p);
});

return promises;
 };

//Function returning a promise
var checkOutData = function(payload) {
  return Csp.update(payload).$promise.then(function(result) {
return result.data
   });
  }

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 JQuery to switch out images that do not have an ID or class assigned

Currently, I am using a Google Chrome Extension to apply an external theme to a website. Unfortunately, the logo on the site does not have an ID or class that can be used to call it. I am searching for a solution to replace it with a different image. My ...

Unlinked Checkbox in Angular Bootstrap Modal Controller

I am currently utilizing the modal feature from Bootstrap 3's Angular fork, and I am facing an issue with using a checkbox within the modal and retrieving its value in my main controller. The checkbox value is properly bound in the view but not in th ...

Problem with jQuery's .prepend method being called twice on list items

Looking to enhance the appearance of a list by adding some icons before the anchor links within each list item. <ul class="submenu-children"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> ...

What is the best method for embedding JSON data into a script tag within a Zope Chameleon template?

Creating a pyramid/python application where the view callable passes in an array variable called data, structured as [[[x1,y1,z1,],...],[[v1,v2,v3],...]] In the view callable: import json jsdata = json.dumps(data) I aim to place this data within a java ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...

Looking for a script to automate clicking on a specific web element using JavaScript

When working with Selenium, we utilize an action to interact with an element by clicking on it at specific coordinates (X, Y). action.MoveToElement(element, X, Y).Click().Build().Perform() I am looking to achieve the same functionality using Javascript. ...

Unable to execute controller due to service call testing failure

I'm currently working on writing a code to test the service call in my controller. The goal is to unit test a specific function within the controller that makes the service call and retrieves data. While I am using local JSON for testing purposes, the ...

The challenge of scoping in Angular directives

Although I have some experience with Angular, I am still struggling with a particular issue. I am using a directive2 that is transcluded through another directive1. Both directive1 and a controller are on the same element and share the same scope. My inten ...

Table borders disappear when loading PHP echoed tables with jQuery and Ajax

Currently, I am delving into the world of jQuery, PHP, AJAX, and MySQL. My objective is to retrieve a table from the MySQL server and exhibit it on a webpage. This involves two PHP files – one serves as the back-end script connecting to the database and ...

Using Material UI with Reactjs for Background Image Mapping

I need some advice from everyone. I have an array of images and I've mapped the content, but for some reason I am unable to set a background image in the styles of a component. The other objects in the array are working as expected. {DlCards.map((mdlc ...

Basic asynchronous JavaScript and XML (AJAX) call

I am currently learning about ajax and experimenting with a script that involves extracting information from a JSON object and displaying it on the document. Below is an example of the JSON file named companyinfo.json: { 'id':1, 'name&apos ...

Having trouble dynamically adding elements to the Semantic-UI Accordion component

I have a challenge involving inserting dynamic content into a Semantic-UI Accordion. My goal is to display JSON data as an Accordion in the HTML. Below is the script and HTML I am using for this purpose: <script language='javascript'> ...

Download function in Express.JS failing to retrieve file

I have been working on a Node.JS server using Express to generate and download PDFs based on user input. Previously, I used the <form action=""> method to call my API, but switched to Axios due to Netlify not supporting NuxtAPI. The program ...

When I try to pass a variable as a prop to another .js file, it mysteriously transforms into an undefined value

Upon successful login, my app file sets the isAuthenticated variable to true and redirects to the /admin page. The Firebase API call is functioning as expected, allowing access only with a valid username and password. The issue arises when I try to hide t ...

The fancybox's excess content is concealed

I've recently integrated fancybox 2 into my project and have encountered an issue when appending HTML content to the modal. I disabled scrolling, but now any overflowing content is being hidden. Could this be related to the max-height of the modal? Ho ...

Limit selection choices in select element

Similar Question: Prevent select dropdown from opening in FireFox and Opera In my HTML file, I have a select tag that I want to use to open my own table when clicked. However, the window of the Select tag also opens, which is not desirable. Is there a ...

What methods are most effective for exchanging data between AngularJS and MVC5?

I'm facing some challenges when it comes to transferring data between AngularJS and MVC5 in the context of creating a single page application (SPA). What is the most effective way to integrate AngularJS with MVC - using controllers or APIs? I came a ...

Send location data to the PHP server through AJAX and then fetch it in JavaScript once it has been handled

I am looking to transfer coordinates from client-side JavaScript to server-side PHP using Ajax, and then retrieve the processed result back to JavaScript for further use. While I have managed to pass the data to PHP successfully, I am struggling to figure ...

Issue encountered in Angularjs during upgrade process from version 1.2.27 to 1.4.7

Recently, I upgraded my app from using AngularJS 1.2.27 to version 1.4.7, but now I am encountering an error in the AngularJS file. SyntaxError: Unexpected token : (angular.js:12477) at Function (native) at Object.sd. ...

The error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...