You should use $ q.all with an array of promises and return a joint promise. This only promise will be rejected if one of the internal promises fails.
this.storeNameValidate = function (stores) { var promises = Object.keys(stores).map(function(storeIndex) { return this.nameValidate(stores[storeIndex].storeName, 3, 10).then(function () { console.log("valid store name"); }, function () { return $q.reject("invalid store name"); }); }, this); return $q.all(promises); };
In addition, do not abuse $q.defer , you do not need it in your case. Such excessive use of it is called a deferred anti-pattern .
In addition, if the error message you are about to reject is always an “invalid repository name” (not specified in the repository), and you do not need to pre-create additional actions in the checked repositories, you can omit errors and successful callbacks too. Then the code becomes even cleaner:
this.storeNameValidate = function (stores) { var promises = Object.keys(stores).map(function(storeIndex) { return this.nameValidate(stores[storeIndex].storeName, 3, 10); }, this); return $q.all(promises); };
source share