I am currently working on an Angular service that involves making HTTP calls. Here is an overview of the code structure:
this.checkAndSendNotifications = function() {
UsersService.getArray(function(array) {
var notifications = [];
angular.forEach(array, function(element) {
if (some conditions are met) {
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 am facing a challenge where I need to ensure that the printNotificationsStatus() function is called only after all API calls are completed to guarantee that all API responses are received. Currently, the function is being called at the end of the angular.forEach execution, which could lead to asynchronous API promises being resolved later than expected.
Is there a solution to synchronize the API calls?
Thank you in advance, Davide