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

Trigger the function upon displaying the modal

Within my Bootstrap project, I have set up a click event to trigger a modal as follows: $('#make_selects_modal').appendTo("body").modal('show'); My requirement is to run a function called pickClient when this modal is displayed. I att ...

receiving unexpected data while using AJAX

For my PHP project, I have a function that validates a textbox using AJAX. The AJAX is working fine, but it only gives the following output for $return_value==-4 "<br /> <font size='1'><table class='xdebug-error xe-deprecated ...

Retrieving data from $resource in AngularJS and accessing it in $scope

I've created an API that sends JSON data to $resource. In my controller, I am attempting to retrieve a specific row with the following code: $scope.company = Companies.query({id: companyId}); But when I try to display the 'company_name' i ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

Meta tag information from Next.js not displaying properly on social media posts

After implementing meta tags using Next.js's built-in Head component, I encountered an issue where the meta tag details were not showing when sharing my link on Facebook. Below is the code snippet I used: I included the following meta tags in my inde ...

Use jQuery to permit only numeric characters and the symbol "-" to be entered into a textbox

I have been working on a JQuery script that only allows users to input numbers in a text field. However, I am now trying to modify the code to also allow users to enter "-" (hyphen), but so far it's not working as expected. If anyone can provide assis ...

Navbar collapse not functioning properly on HTML, CSS, and JavaScript

I have developed a CSS code snippet: .nav{ right: 0px; left: 0px; margin-top: 0px; margin-bottom:20px; height: 35px; text-align: center; background-color: red; z-index: 1; } .sticky { background: #000; text-align: center; ...

Is there a way I can implement a user-friendly playlist feature in my object-oriented HTML5 JS audio player that allows users

I have created a functional audio player using HTML5 and Javascript, along with some basic CSS. However, I am looking to enhance it by adding a clickable playlist feature. I want the name of the currently playing audio track to be displayed, and users shou ...

Ajax cannot seem to come to a resolution

After completing my learning on Ajax, I decided to work on a simple project - a port scanner. However, I am facing issues with it as it is not working properly. The only message that pops up is 'Scan started' and I can't figure out what the ...

Node.js proxy request to elastic search has been experiencing freezing issues

I attempted to send a request to my Elasticsearch server (localhost:9200) from my own server at localhost:8080. However, I am not receiving any response from the Elastic search. This is the code I used: var express = require('express'); var rout ...

When invoking a function, a React Component utilizes the props from the first element instead of its own

Whenever I try to invoke a function of a component, it seems to be replacing the parameters and passing the props of the first array element instead of the selected one. To illustrate this issue, let's take a look at some code: Firstly, here is how ...

Images flicker as they transition

Within my HTML body, I have the following: <a id="Hal9000"> In addition, there is a function included: function Hal(MSG){ document.getElementById("Hal9000").innerHTML = "<img src=\"+preloadImage("HAL9000.php?Text="+MSG)+"\"\>" ...

Can I link the accordion title to a different webpage?

Is it possible to turn the title of an accordion into a button without it looking like a button? Here is an image of the accordion title and some accompanying data. I want to be able to click on the text in the title to navigate to another page. I am worki ...

Button Triggering Javascript

Looking for a handy solution that allows users to either accept or reject a website's cookie policy. I came across an interesting library called cookies-EU-Banner (found at ) which seems to be quite popular. It recognizes when the user clicks on Reje ...

Can I monitor when a $http request is being processed?

One of the functions in my service is as follows: self.$http({ url: xxx, method: "DELETE" }) .success((): void => { }); I am looking for a way to dynamically disable a button on my html page while the $http call is being made. Is there a sol ...

Experiencing an issue in Test Cafe when attempting to click on an invisible link using the Client Function

I need to find a way to click on an invisible button in HTML. I attempted to use ClientFunction, however I encountered an error related to the element. import { Selector,ClientFunction } from 'testcafe'; fixture('Clicking Invisible link&apo ...

Modify the layout of the date selector to display weekdays instead - material ui

How can I change the datepicker format to display weekdays (Monday, Tuesday,..) instead of MM/dd/yyyy? Currently, the datepicker is set up with the format format="MM/dd/yyyy". Would it be possible to modify this? Here is the source code: <MuiPickers ...

I am struggling to grasp the concept of how the g flag in JavaScript's string.match(regexp) method operates

In the JavaScript book "The Good Parts", there is an explanation of the method string.match(regexp): The match method works by comparing a string with a regular expression. Its behavior varies based on whether or not the g flag is present. Without the g ...

Incorporate and interpret a custom JSON object within my Shopify Liquid theme

In an attempt to integrate custom data into my Shopify liquid theme, I stored a JSON file in the assets folder. My goal is to retrieve and parse this JSON object within a jQuery method from a JavaScript file also located in the assets folder. Despite try ...

What are some ways to customize the appearance of the Material UI table header?

How can I customize the appearance of Material's UI table header? Perhaps by adding classes using useStyle. <TableHead > <TableRow > <TableCell hover>Dessert (100g serving)</TableCell> ...