【发布时间】:2017-10-06 19:41:33
【问题描述】:
我正在尝试让某些 api 调用以正确的顺序运行。用户选择他们选择运行的月份(例如 10 月、11 月、12 月)。我正试图让他们按顺序开火。十月、十一月、十二月(不是十二月、十月、十一月)
第一个函数是一个 If 语句,如果整个数组都存在,我可以让它按顺序运行,但当他们开始调整它时,我无法保持顺序正常。
所以 getStationsInOrder 可以很好地处理回调 - 但我似乎无法让循环以正确的顺序将月份发送到交换机。我已经从开关中删除了返回,所以它不只是以月份结束,在数组中是第一个
例子。用户仅选择 11 月、12 月、1 月 - 按顺序触发这些 api 调用。月份在传递给 for 循环的数组中,然后循环将其传递给交换机。
感谢您提供的任何帮助。
noaaData: function () {
console.log(this.checkedMonths, 'Months Selected')
//if all checked get all data, array smaller than 7 get
selected stations
if (!this.checkedMonths || this.checkedMonths.length == 7){
//trigger this function - runs api.get's in order
this.getStationsInOrder(this.userFIPS, function(){
console.log('Done here move on')
})
} else {
//this does NOT run in order - there by messing up all other equations
this.getStationsChecked(this.userFIPS)
}//end else
},
getStationsChecked: function (userFIPS){
for (var i = 0; i < this.checkedMonths.length; i++) {
console.log(this.checkedMonths[i], 'month in ooop')
switch (this.checkedMonths[i]) {
case 'October':
this.getStationsOct(userFIPS)
break;
case 'November':
this.getStationsNov(userFIPS)
console.log('nov')
break;
case 'December':
this.getStationsDec(userFIPS)
console.log('dec')
break;
case 'January':
this.getStationsJan(userFIPS)
console.log('jan')
break;
case 'February':
this.getStationsFeb(userFIPS)
console.log('feb')
break;
case 'March':
this.getStationsMar(userFIPS)
console.log('mar')
break;
case 'April':
this.getStationsApr(userFIPS)
console.log('apr')
break;
default: 'Error getStationsChecked default case'
}
}
},
getStationsInOrder: function(userFIPS, callback){
self = this
// series of callbacks to run each in order - oct thru
// April - triggered in if statement in noaaData()
self.getStationsOct(userFIPS, function(){
self.getStationsNov(userFIPS, function(){
self.getStationsDec(userFIPS, function(){
self.getStationsJan(userFIPS, function(){
self.getStationsFeb(userFIPS, function (){
self.getStationsMar(userFIPS, function(){
self.getStationsApr(userFIPS, callback)
})
})
})
})
})
})
},
【问题讨论】:
-
由于您预期目标的异步性质,我建议利用回调的类和
done或completed方法。
标签: javascript loops switch-statement vuejs2