我的for循环中有ajax请求,我正在尝试打印迭代索引的值' i'在每次迭代中。我在for循环中使用包装函数(在许多帖子中建议)来执行ajax。但是当我打印控制台的值时,它会以随机的方式打印出来。每次我运行for循环时,它都是不同的。
这是我的for循环和包装函数
get_process_status(){ //new
for(var i=0; i<this.state.current_auto_video_jobs_urls.length; i++){
this.get_auto_video_jobs_array(i)
}
}
//wrapper function
get_auto_video_jobs_array(i){
var that = this;
var settings_3 = {
"async": true,
"crossDomain": true,
"url": that.state.current_auto_video_jobs_urls[i],
"method": "GET",
"headers": {
Authorization: "Token " + that.props.token_Reducer.token
},
success: function (response, textStatus, jQxhr) {
console.log("success")
console.log("value of i is " + i)
},
}
$.ajax(settings_3).done((response) => {
auto_video_jobs_array.push(response)
if(i == that.state.current_auto_video_jobs_urls.length -1 ){
console.log("i reached last value")
that.setState({current_auto_video_jobs: auto_video_jobs_array})
console.log("current jobs are" + that.state.current_auto_video_jobs)
}
});
}
控制台输出
你可以看到2次,i打印的值是不同的序列。为什么每次循环运行时序列只能是0到9?
答案 0 :(得分:0)
因为名称建议(异步Javascript和XML)的AJAX是异步,这意味着它不会按顺序运行。
要使代码工作,您必须将循环放在Ajax请求的from flask import Flask, jsonify, request
from flasgger import Swagger
from rulesEnginePy.RiskOfCancellation.RiskOfCancellation import
RiskOfCancellation
from logging.handlers import RotatingFileHandler
import logging
from datetime import datetime
app = Flask(name)
Swagger(app, template={
'swagger': '2.0',
'info': {
'title': 'RRRE RofCXL API',
'description': 'API for RRRE (Right Revenue Rules Engine) RofCXL (Risk of
Cancellation)',
},
'basepath': '/api',
})
log_handler = RotatingFileHandler(app.root_path + '/../logs/rrre.log',
maxBytes=10000000, backupCount=10)
log_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(pathname)s:%(lineno)d | %
(funcName)s | %(levelname)s | %(message)s')
log_handler.setFormatter(formatter)
app.logger.addHandler(log_handler)
@app.route('/api//calculate/4', methods=['GET'])
def calculate4(name):
try:
app.logger.info('About to use service %s' % name)
sampleDate = datetime.strptime(request.args.get('date'), '%Y-%m-%d')
# for id, sample in samples.items():
WOM = calculators[name].week_of_month(sampleDate)
DOW = sampleDate.weekday()+1
riskOfCancellation = RiskOfCancellation.calculateRiskOfCancellationMOYDOW(int(sampleDate.month),int(DOW))
app.logger.info(
'Calculated Risk of Cancellation {0} for DOM {1}, DOW {2}, WOM {3} and MOY
{4}'.format(
riskOfCancellation,
sampleDate.day,
DOW,
WOM,
sampleDate.month
)
)
calculations = {
'DOM': sampleDate.day,
'DOW': DOW,
'WOM': WOM,
'MOY': sampleDate.month,
'riskOfCancellation': riskOfCancellation
}
app.logger.info('Done making calculations for request for calculate 4')
return jsonify({
'data': calculations,
})
except KeyError:
return jsonify({
'errors': [{
'code': '1000',
'title': 'A service with the given name doesn't exist',
}],
}), 404
处理程序