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

165 Views Asked by At

I'm facing some difficulties while trying to understand why $q.all returns the response of the last promise in array, for all promises given:

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;
    });
}

End-points are all the same, the only thing I change on each request is one element (key element) in 'postData' object.

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

postData :

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

getPostData:

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

There are 2 best solutions below

0
georgeawg On BEST ANSWER

Use angular.copy to make a new copy of the data for each request:

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

The issue is happening because postRequest is global, hence the object is altered three times but the same object is used. Either use angular.copy, either use JSON.parse and JSON.stringify, either just declare the object inline.

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