Jintu J Jintu J - 1 month ago 15
AngularJS Question

Resolving Promises asyncronously

I have 2 different loops that perform POST and DELETE operations respectively.
Once, the all the operations are complete, I want to make another service request.

my issue is :
In case of error on delete operation, the control goes to the catch block and a dialog confirmation is needed to decide if the item still needs to be deleted.

If a confirmation comes from the dialog, I want to make a permanent delete to the id and which is happening. But Somehow refresh is invoked earlier than I want. I miss something fundamental here.
Please help...

function submitAndRefresh(){
var deletePromisesTasks = [];
var addPromisesTasks = [];

angular.forEach(toBeDeleted, function(value,key){
deletePromisesTasks.push(delete(value.id));
});

angular.forEach(toBeAdded, function(value,key){
addPromisesTasks.push(add(value));
});

//To be performed after all the add/delete operations are completely done!
$q.all(deletePromisesTasks,addPromisesTasks).then(function(){
refreshData(); //Another Service Call
});
}

function delete(id, purge_flag) {
var defer = $q.defer();
deleteOrPurge(id, purge_flag).then((promise1) => {
defer.resolve();
}).catch(function(error) {
confirmAndDeleteContractParameters(error, delete, id, true);
}).finally(function(){
return defer.promise;
});
}

function deleteOrPurge(id, purge_flag){
return Service.items().delete({
id: id,
purge_flag: purge_flag || false
}).$promise;
}



function confirmAndDelete(error, callback, parameterId, purge_flag) {
var confirmModal = {
header: 'Confirm',
showCancelButton: true
};
try {
confirmModal.body = 'Some msg. Do you want to continue?';
} catch (e) {}
ModalService.confirmDialog($scope, confirmModal, function(confirm){
if (confirm) {
callback(parameterId, purge_flag);
}
});
}

Answer

As a basic rule, when you have a function started with var defer = $q.defer();, the last line of the function should usually be return defer.promise

Comments