Davide Campello Davide Campello - 20 days ago 5
AngularJS Question

Angular execute function after multiple API call

I'm writing a angular service that make some http call.
The code is something like this.

this.checkAndSendNotifications = function() {

UsersService.getArray(function(array) {

var notifications = [];
angular.forEach(array, function(element) {

if (some conditions is true) {
srv.sendNotificationToToken(element.id,
function() {
notifications.push({
id: user.id,
errorStatus: null,
errorStatusText: null
});
},
function(error) {
notifications.push({
id: user.id,
errorStatus: error.status,
errorStatusText: error.statusText
});
});
}

printNotificationsStatus(notifications);
});
});
};

this.sendNotificationToToken = function(id, onSuccess, onError) {
$http({
method: 'POST',
url: 'https://url....',
headers: {
'Authorization': 'Bearer ....',
'Content-Type': 'application/json'
},
data: {
"id": id,
"message": "hello"
}
}).then(function successCallback(response) {
onSuccess();
}, function errorCallback(error) {
onError(error)
});
};


I need to call the printNotificationsStatus() function only at the end of all api calls to be sure to have all api response but now the function is called at the end of angular.forEach execution and the API's promise can be resolved later because they are asyncronous.

Is there a way to wait?

Thanks in advance
Davide

Answer

You can use $q.all to wait all promises to be resolved. Like this:

UsersService.getArray(function(array) {

    var promises = [];
    var notifications = [];
    angular.forEach(array, function(element) {

        if (some conditions is true) {
            var promise = srv.sendNotificationToToken(element.id,
                function() {
                    notifications.push({
                        id: user.id,
                        errorStatus: null,
                        errorStatusText: null
                    });
                },
                function(error) {
                    notifications.push({
                        id: user.id,
                        errorStatus: error.status,
                        errorStatusText: error.statusText
                    });
                });
            promises.push(promise);
        }

    });

    // wait all promises and resolve
    $q.all(promises).then(function () {
        printNotificationsStatus(notifications);    
    })

 });
};

don't forget inject $q.

Ps: in your code you are executing printNotificationsStatus() after the first iteration.