Javascript 在get请求中使用$interval
我在init中调用了两个API,但是在第二个get请求中,我希望它继续调用它,直到满足我的案例中的一个特定条件,并且传递了2个日期范围。条件是,在日期差小于15天之前,继续调用API,然后停止API调用 我的代码是这样的Javascript 在get请求中使用$interval,javascript,angularjs,promise,momentjs,intervals,Javascript,Angularjs,Promise,Momentjs,Intervals,我在init中调用了两个API,但是在第二个get请求中,我希望它继续调用它,直到满足我的案例中的一个特定条件,并且传递了2个日期范围。条件是,在日期差小于15天之前,继续调用API,然后停止API调用 我的代码是这样的 var startDate=moment(new Date()).format("YYYY-MM-DD"); var endDate; $scope.init=function(){ firstGetFunction().then(function(response1){
var startDate=moment(new Date()).format("YYYY-MM-DD");
var endDate;
$scope.init=function(){
firstGetFunction().then(function(response1){
let i=0;
$interval(function() {
endDate=moment(startDate).add(i++,'days').format("YYYY-MM-DD");
if(new moment.duration(new Date(endDate)-new Date(startDate)).asDays()<=15){
secondGetFunction(startDate,endDate).then(function(response2){
$scope.obj1=response1;
$scope.obj2=response2;
});//2nd API call ends
}//if diff is less than 15 days
else{
return;
}
},100);//$interval ends
});//1st API call ends
}
我面临的问题是我无法退出$interval。
是否有更好的方法来处理此Get请求?
代码可以改进吗?尝试以下方法:
var startDate=moment(new Date()).format("YYYY-MM-DD");
var endDate;
$scope.init=function(){
firstGetFunction().then(function(response1){
let i=0;
let timer = $interval(function() {
endDate=moment(startDate).add(i++,'days').format("YYYY-MM-DD");
if(new moment.duration(new Date(endDate)-new Date(startDate)).asDays()<=15){
secondGetFunction(startDate,endDate).then(function(response2){
$scope.obj1=response1;
$scope.obj2=response2;
});//2nd API call ends
}//if diff is less than 15 days
else{
$interval.cancel(timer);
}
},100);//$interval ends
});//1st API call ends
}