Dreamweaver Dreamweaver - 2 months ago 15
AngularJS Question

Need help in resolving nested promises, Promises are not getting resolved

I have a service designed which takes some parameter and then loops through input array, and find out which item is empty and then add those to and array and then after $q.all resolved it should give me the array of empty items.

input is array of items

function getElements(inputs) {
var elements= [],
promise, whenPromise,
promises = [],
mainPromise = $q.defer();
if (inputs.length === 0) {
mainPromise.resolve(elements);
return mainPromise.promise;
}

angular.forEach(inputs, function (input) {
promise = getPromises(input);
whenPromise = $q.resolve(promise).then(function (response) {
$timeout(function() {
if (response.isEmpty) {
**//perform action with the response.data;**
}
});
}, function () {

});

promises.push(whenPromise);
});


$q.all(promises).finally(function () {
mainPromise.resolve(outdatedEntities);

});

return mainPromise.promise;
}

function getPromises(input) {
var deferred = $q.defer();

someSerivce.getItemDetails(input.Id).then(function (value) {
if (value === null) {
$timeout(function () {
deferred.resolve({data: input, isEmpty: true});
});

} else {
//have item locally, but need to see if it's current
input.isEmpty().then(function (isEmpty) {
$timeout(function () {
deferred.resolve({data: input, isEmpty: isEmpty});
});
}, function (error) {
deferred.reject(error);
});
}

});

return deferred.promise;
}


Now, the problem is the $q.all is never resolved. Even though all the internal promises are getting resolved.

Answer

This should work:

function getElements(inputs) {
    var elements = [],
            promise, whenPromise,
            promises = [],
            mainPromise = $q.defer();
    if (inputs.length === 0) {
        mainPromise.resolve(elements);
        return mainPromise.promise;
    }

    angular.forEach(inputs, function (input) {
        promise = getPromises(input);
        whenPromise = promise.then(function (response) {

            if (response.isEmpty) {
                * *//perform action with the response.data;**
            }

        }, function () {

        });

        promises.push(whenPromise);
    });


    return $q.all(promises).finally(function () {
        return outdatedEntities;
    });
}

function getPromises(input) {
    return someSerivce.getItemDetails(input.Id).then(function (value) {
        if (value === null) {
            return {data: input, isEmpty: true};
        } else {
            //have item locally, but need to see if it's current
            return input.isEmpty().then(function (isEmpty) {
                return {data: input, isEmpty: isEmpty};
            }, function (error) {
                return error;
            });
        }
    });
}