I have a function that calls web service calls on my server and returns an array of promises.
However, some of these calls may work, while others may not. The way my function is currently configured, if one of them fails, it warns that the whole thing has failed. If I make 5 calls, 1 may fail. I need to spell it correctly, and I'm not sure how to do it.
The ideal answer / log would be:
- call 1 passed
- call 2 passed
- call 3 passed
- call 4 failed - reason
- challenge 5 passed
Currently, all of this will return “Descriptor User Operation Failed” because call 4 failed.
Function:
var manageGroup = function (add, group, users){
var deffered = $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 "
for (var i = 0; i < usersLength; i++){
arrPromises[i] = $().SPServices({
operation: operation,
groupName: group.name,
userLoginName: users[i].domain
});
}
$q.all(arrPromises).then(
function (){
for (var i = 0; i < usersLength; i++){
console.log(actionText + users[i].name + actionText2 + group.name);
};
deffered.resolve();
},
function (){
alert('The handle user operation failed.');
}
)
return deffered.promise;
}
promises , $q.all, :
:
/*$q.all(arrPromises).then(
function (){
//when promises are finsihed
for (var i = 0; i < usersLength; i++){
console.log(actionText + users[i].name + actionText2 + group.name);
};
deferred.resolve();
},
//function incase of AJAX failure
function (){
alert('The handle user operation failed.');
}
) */
:
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();
})