尝试发送角度动态数组的promises来表达服务器

时间:2015-08-05 02:21:30

标签: javascript angularjs express angular-promise

我正在尝试向一个快速应用程序发送一组promise,以从mongo数据库中获取数据。它似乎在前端表现正确。在此示例中,两个对象都发送到服务器,并使用$ q.all解析。但是当我调试服务器时,我发现两个对象是相同的。在这种情况下,它是有效负载2的最后一个承诺,它被解析了2次。如果我添加更多的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){
          //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
   });
  }

1 个答案:

答案 0 :(得分:1)

原因是因为你不断修改有效负载param,它是一个对象,因此通过引用传递,因此每次更改它时,它都会修改它的所有引用,包括那些已经添加到promises数组中的引用。

---
title: "Untitled"
author: "Jeb"
date: "August 4, 2015"
output: html_document
---


This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r}
table(cars.by.name$make)
```  

```{r}
summary(cars)
summary(cars.by.name)
```

```{r}
table(cars.by.name)
```   
You can also embed plots, for example:

```{r, echo=FALSE}
plot(cars)
plot(cars.import)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.