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