Javascript Angularjs处理嵌套承诺
我的申请表中有以下代码Javascript Angularjs处理嵌套承诺,javascript,angularjs,angular-promise,Javascript,Angularjs,Angular Promise,我的申请表中有以下代码 $scope.addZero = function(x,n) { while (x.toString().length < n) { x = "0" + x; } return x; } $scope.msToTime = function() { var d = new Date();
$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());
});
我希望它是像主最终应该来后,内循环结束。如何按顺序处理嵌套的承诺。我在内部承诺中添加了“return$scope.myCall;”,但这也只会等待第一个“then”,其余的都会被忽略。
第二,为什么每次EndTime更改时StartTime都会更改,而当main启动时它应该只更改一次?请帮忙。
非常感谢 您需要返回由
$interval
返回的承诺
您已将$scope.myCall
分配给$interval
返回的承诺,但不会将其返回给外部承诺。如果您在定义如下的同一代码块中返回该承诺:
.then(function () {
$scope.myCall = $interval(function() {
}, 1000,2);
return $scope.myCall;
})
.then(function(){
})
.catch(function error(errmsg){
})
.finally(function(){
})
然后,它将为您提供所需的结果:
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
Main finally TimeInSeconds >10:52:11:687
finally TimeInSeconds >10:52:11:687
谢谢@Matthew。成功了。但有一个疑问。为什么“finally TimeInSeconds”在“Main finally”之后。我只是在求知。那么$scope.StartTime呢?事实上,我并不完全确定。如果其他任何人能发表任何评论,我都会非常欢迎,我自己也会从中学到一些东西!实际上它不起作用。因为它只接受顺序中的第一个“then”函数。如果我们在内部承诺中添加mode-then函数,这些函数在“Main-finally”之后执行
.then(function () {
$scope.myCall = $interval(function() {
}, 1000,2);
return $scope.myCall;
})
.then(function(){
})
.catch(function error(errmsg){
})
.finally(function(){
})
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
Main finally TimeInSeconds >10:52:11:687
finally TimeInSeconds >10:52:11:687