I am facing an issue with my function that calls web services on my server and returns an array of promises.
The problem is that if one of the calls fails, the entire process is marked as a failure. For example, out of 5 calls, 1 might fail, causing the whole function to fail. I need a way to properly log this information but I'm unsure how to proceed.
An ideal log would look like:
- call 1 passed
- call 2 passed
- call 3 passed
- call 4 failed - reason
- call 5 passed
Currently, the function returns "The handle user operation failed" when call 4 fails.
Function:
var manageGroup = function (add, group, users){
var deferred = $q.defer();
var arrPromises = [];
var promiseIndex = arrPromises.length;
var usersLength = users.length;
var operation = add ? "AddUserToGroup" : "RemoveUserFromGroup";
var actionText = add ? "Added: " : "Removed: ";
var actionText2 = add ? " to " : " from ";
//Apply operation on selected groups
for (var i = 0; i < usersLength; i++){
arrPromises[i] = $().SPServices({
operation: operation,
groupName: group.name,
userLoginName: users[i].domain
});
}
$q.all(arrPromises).then(
function (){
//when promises are finished
for (var i = 0; i < usersLength; i++){
console.log(actionText + users[i].name + actionText2 + group.name);
};
deferred.resolve();
},
//function in case of AJAX failure
function (){
alert('The handle user operation failed.');
}
)
return deferred.promise;
}
I attempted to handle promises individually instead of using $q.all, but now nothing is being logged:
I removed this section:
/*$q.all(arrPromises).then(
function (){
//when promises are finished
for (var i = 0; i < usersLength; i++){
console.log(actionText + users[i].name + actionText2 + group.name);
};
deferred.resolve();
},
//function in case of AJAX failure
function (){
alert('The handle user operation failed.');
}
) */
And introduced this instead:
for (var i = 0; i<promiseIndex; i++){
arrPromises[i].then(
function (){
console.log(actionText + user[i].name + actionText2 + group.name);
}
),
function (){
alert('Failed to add/remove'+ user[i].name + ' to ' + group.name)
}
}
$q.all(arrPromises).then(function (){
deferred.resolve();
}, function (){
deferred.reject();
})