I have a checkbox with 3 selections on the UI, each checkbox selection will represent an independent service to fulfill. However, since these services are variably invoked, I need to come up with a way to wait for all selected options to complete until showing messaging.
so basically, initial implementation was this:
if (doA) {
mysvc.doA();
}
if (doB) {
mysvc.doB();
}
if (doC) {
mysvc.doC();
}
window.alert('success');
Then I realized I need to wait for all of them to complete, so I came up with this:
if (doA) {
mysvc.doA();
}
if (doB) {
mysvc.doB();
}
if (doC) {
mysvc.doC();
}
setTimeout(function () {
window.alert('success');
}, 8000);
Because the operations typically take at maximum of 8 seconds to complete if all selected. But this is obviously not ideal. Also, I would ultimately like to give feedback for each individual operation at the end. Any helps or resources will be appreciated.
you can use $q.all:
var promises = [];
if (doA) {
promises.push(mysvc.doA);
}
if (doB) {
promises.push(mysvc.doB);
}
if (doC) {
promises.push(mysvc.doC);
}
$q.all(promises).then(function(d){
window.alert('success');
})
Can you attach a variable to each call then only show success when they're all true?
var doaCheck = false;
var dobCheck = false;
var docCheck = false;
if (doA) {
mysvc.doA();
doaCheck = true;
}
if (doB) {
mysvc.doB();
dobCheck = true;
}
if (doC) {
mysvc.doC();
docCheck = true;
}
if (doaCheck && dobCheck && docCheck ) {
window.alert('success');
// code to reset
}
The most proper way to do this is with promises using angular's $q . Each function should return a promise, then you can take all 3 promises and use $q.all to combine them together and have a callback function that runs only once all 3 are done. Here's an example with $http promises , but you can do it for anything by creating your own promises using $q.defer() as done here: example using $q.defer()
q1 = $scope.q1 = $q.defer(),
q2 = $scope.q2 = $q.defer(),
p1 = $scope.q1.promise,
p2 = $scope.q2.promise;
$scope.fromThen = $q.all([
p1.then(thenFn),
p2.then(thenFn)
])
.then(function(values) {
console.log(values);
return values;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.