$q.all returns 对数组中所有承诺的相同响应

$q.all returns same response for all promises in the array

我在尝试理解为什么 $q.all returns 数组中最后一个承诺的响应时遇到了一些困难,对于给定的所有承诺:

function getGlobalData() {
    $q.all(
        [
        genericApi.submitPostRequest(getPostData('firstKey')),
        genericApi.submitPostRequest(getPostData('secondKey')),
        genericApi.submitPostRequest(getPostData('specialKey'))
        ])
    .then(function(results){
        vm.globalObject['firstKey'] = results[0].data;
        vm.globalObject['secondKey'] = results[1].data;
        vm.globalObject['specialKey'] = results[2].data;
    });
}

端点都是一样的,我对每个请求唯一改变的是 'postData' 对象中的一个元素(关键元素)。

function submitPostRequest(data) {    
    return $http({
        method: 'POST',
        data: data,
        url: 'https://someUrl',
        headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer someToken'
        }
    });
}

发布数据:

var postRequest = {
  'endtime' : null,
  'key' : null, 
  'arr' : ['diff','core'],
  'starttime' : null
};

getPostData:

function getPostData(key){
    postRequest.key = key;
    return postRequest;
}

使用angular.copy为每个请求制作数据的新副本:

function getPostData(key){
    var req = angular.copy(postRequest);
    req.key = key;
    return req;
}

问题的发生是因为 postRequest 是全局的,因此对象被更改了三次,但使用的是同一个对象。要么使用 angular.copy,要么使用 JSON.parseJSON.stringify,要么只声明内联对象。

function getPostData(key){
   var postRequest = {
     'endtime' : null,
     'key' : null, 
     'arr' : ['diff','core'],
     'starttime' : null
   };
   postRequest.key = key;
   return postRequest;
}