I have below code in my application,
$scope.addZero = function(x,n) {
while (x.toString().length < n) {
x = "0" + x;
}
return x;
}
$scope.msToTime = function() {
var d = new Date();
var h = $scope.addZero(d.getHours(), 2);
var m = $scope.addZero(d.getMinutes(), 2);
var s = $scope.addZero(d.getSeconds(), 2);
var ms = $scope.addZero(d.getMilliseconds(), 3);
return h + ":" + m + ":" + s + ":" + ms;
}
var Deferred = $q.defer();
Deferred.resolve('outer success');
var promise = Deferred.promise;
promise
.then(function () {
var anotherDeferred = $q.defer();
console.log("Main Start "+"TimeInSeconds >"+$scope.msToTime());
$scope.StartTime = $scope.msToTime
$scope.myCall = $interval(function() {
anotherDeferred.resolve('inner success');
var anotherpromise = anotherDeferred.promise;
anotherpromise
.then(function (data) {
console.log("Inner Start "+"TimeInSeconds >"+$scope.msToTime());
return Myservice.db('mytable');
})
.then(function (data) {
console.log("Inner check 1 ");
$scope.EndTime = $scope.msToTime
})
.catch(function error(errmsg) {
console.error(errmsg);
})
.finally(function() {
console.log("finally "+"TimeInSeconds >"+$scope.msToTime());
});
}, 1000,2);
return $scope.myCall;
})
.then(function() {
console.log("Done");
})
.catch(function error(errmsg) {
console.error(errmsg);
})
.finally(function() {
console.log("Main finally "+"TimeInSeconds >"+$scope.msToTime());
});
And referring $scope in html like this,
<div>{{StartTime()}}</div> </br>
<div>{{EndTime()}}</div>
The problem is , things are not working in sequentially as expected. When i take console output , it is as below.
Main Start TimeInSeconds >10:52:09:686
Inner Start TimeInSeconds >10:52:10:687
finally TimeInSeconds >10:52:10:690
Inner Start TimeInSeconds >10:52:11:687
Done
Inner check 1
Main finally TimeInSeconds >10:52:11:687
finally TimeInSeconds >10:52:11:6879
I expect it to be like Main finally should come after inner loop is over. How can i handle nested promises in sequence. I added "return $scope.myCall;" to inner promise but that also waits only the first "then" and rest is ignored. Second, why StartTime gets changed every time when EndTime changes, it should be change only once when main starts ? please help. Many thanks in advance.