forループでAJAX呼び出しを行う必要があります。私は、配列内のレスポンスを格納していて、配列の要素が順番に並んでいるので、呼び出しが順番に行われる必要があります。私はasync: false
のために行っていました。彼らのどれも働かなかった。 async: false
を作ることは、私が知っている本当に悪い考えですが、応答を順番に取得する代わりに何ができますか?asyncの代替:false
追加情報:配列をレンダリング要素にマッピングしていますので、試したメソッドのほとんどが「未定義のマップを読み取れません」というエラーが表示されました。私は代替として実装しようとしたが、それは仕事と私は未定義
//initialize index counter
var i = 0;
var that = this;
function next() {
$.ajax({
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){
++i;
if(i >= that.state.current_auto_video_jobs_urls.length) {
// run function here as its the last item in array
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)
} else {
// do the next ajax call
auto_video_jobs_array.push(response)
next();
}
}
});
}
// start the first one
next();
のマップを読み取ることができないというエラーを投げていなかった
auto_video_jobs_array = [];
for (var i = 0; i < this.state.current_auto_video_jobs_urls.length; i++) {
this.get_auto_video_jobs_array(i)
}
get_auto_video_jobs_array(i) {
var that = this;
var settings_3 = {
"async": false, //this is made false to get array element in right sequence
"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)
}
});
}
この何:ここ
は、私が現在やっているものですインクリメンタルシーケンスで応答を得る方法で非同期呼び出しを行う方法が必要です。プロミスが提案する一つの選択肢です。私はそれが初めてです。それが方法ならそれをどう実装するのですか?
あなたが実際に順次リクエストを送信する必要がありますか?または結果が元の順序になるようにするだけですか? –
@KevinB説明に基づいて、彼らは元の順序である必要があるようです。 – JLRishe