I have tried all various way to do so but still didnt figure out how to resolve this.
I have a method iterator that return promise; this method runs for x times in a loop. I want if iterator return rejected promise than it should stop the execution and goes to error bloc.
I have tried with below approach taken from this SO asnwerbut this send the error but execute till the x times.
var foo = function(formdata) {
var d = $q.defer();
CallService.init()
.then(function(response) {
return CallService.fun1(formdata);
})
.then(function(response) {
var row = {1:'one', 2:'two', 3: 'three' };
var promiseArray = [];
if (<key condition true>) {
var promise = Object.keys(row).map(function(i) {
return iterator(i, row[i]).then(function(response){
promiseArray.push(response);
}, function(err){
return $q.reject(err);
});
});
return $q.all(promise); // reject if anyone is rejected, otherwise resolve
}
else {
d.reject({
message: "key condition failed."
});
}
return d.promise;
})
.then(successHandler)
.catch(errorHandler);
};
and here is the function that being called for each loop
var iterator = function(num, data) {
var d = $q.defer();
CallService.fun3()
.then(function(response) {
return CallService.fun4(data)
})
.then(function(response) {
d.resolve(num);
})
.catch(function(err) {
d.reject(err);
});
return d.promise;
};
I want that if iterator send reject for the first time than it should not go for the next and break the loop;
how to achieve that?
I have also tried this way
var d = $q.defer();
for (var k in row) {
if (isCalled) break;
var promise = iterator(k, row[k]);
promise.then(function(response) {
promiseArray.push(response);
}, function(err) {
isCalled = true;
d.reject(err);
});
}
if (!isCalled && promiseArray.length > 0) {
console.log('after for loop', promiseArray);
d.resolve(promiseArray);
}
return d.promise;
but this also fails.. it always executes for all the loop in spite of any reject promise.
edit
I have tried with .reduce method but this is somehow works but I need to send promiseArray ( if any entry is there ) alog with the error. here is my working code.
var first_promise = $q.resolve();
var start_promise = Object.keys(row).reduce(function(promise, key){
return promise.then(function(result){
if(angular.isDefined(result)) // as first_promise results undefined
promiseArray.push(result);
return iterator(key, row[key]);
});
}, first_promise);
start_promise.then(function(res){
return $q.when(promiseArray);
}).catch(function(err){
return $q.reject();
});