Piotr___ Piotr___ - 6 months ago 21
Javascript Question

Promise.all() return an unexpected value

I'm really confused with my bit of code, which is an angularjs service. I tried to use Promise.all to concatenate the two promises that are part of the service, and to send the result to my controller.
The thing is that the object returned by Promise.all is composed by the two same arrays.
My code here, just to be clearer:

batchModule.service('BatchService', ['$http', '$q', '$log', 'MessageboxService', function ($http, $q, $log, MessageboxService) {

let deferred = $q.defer();

this.loadAll = () => {

promise1 = () => {
$http.get(_restApiPath + "/batch/?processtype=IMPORT_CUSTOMER")
// loadLastFiveBatch('IMPORT_CUSTOMER')
.then(function (response) {
deferred.resolve(response.data);
// datas.push(response1);
// console.log(datas);
}, function (error) {
deferred.reject(error);
$log.error(error);
});
return deferred.promise;
};

promise2 = () => {
$http.get(_restApiPath + "/batch/?processtype=IMPORT_LAB_MARGIN")
// loadLastFiveBatch('IMPORT_LAB_MARGIN')
.then(function (response) {
deferred.resolve(response.data);
// datas.push(response2);
// console.log(datas);
}, function (error) {
deferred.reject(error);
$log.error(error);
});
return deferred.promise;
};

Promise.all([promise1(), promise2()])
.then(values => {
console.log(values);
});

};
}]);


The console.log(values) return an object made of 2 equal arrays returned by the IMPORT_CUSTOMER request, when the second argument of the Promise.all is precisely a promise returned by the IMPORT_MARGIN request.
I'have been working on it few hours today but I can't find any solution.
I hope I was clear enough, my english is not great.
Thank you for your answers :-)

Answer Source

Both your promises actually return the same $q.defer(); promise. So you need to drop the deferred anti-pattern (using $q.defer() instead of just return $http.get(..);) and the problem should pretty much solve itself.

So change your code to this:

batchModule.service('BatchService', ['$http', '$q', '$log', 'MessageboxService', function ($http, $q, $log, MessageboxService) {

    this.loadAll = () => {

        promise1 = () => {
            return $http.get(_restApiPath + "/batch/?processtype=IMPORT_CUSTOMER")
                .then(response => response.data, error => {
                    $log.error(error);
                    return $q.reject(error);
                });
        };

        promise2 = () => {
            return $http.get(_restApiPath + "/batch/?processtype=IMPORT_MARGIN")
                .then(response => response.data, error => {
                    $log.error(error);
                    return $q.reject(error);
                });
        };

        $q.all([promise1, promise2])
        .then(values => {
            console.log(values);
        });
    };
}]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download