どうもjavascriptの同期とか非同期の処理がわからなくて四苦八苦している。
取り急ぎpromiseを使うとよいらしいので、作ってみたサンプル。
uploadの処理が終わってから、createとeditをそれぞれ実行して、全部終わってからアラートを出す、というもの。
3つの処理はpromiseでくくっておいて、リターンをresolveに入れておく。
Promise.allを使うとまとめて実行できる、リターンも配列にまとまって返ってくる。
upload().then(function(response) {
Promise.all( [create(response), edit(response)] ).then(function(res) {
alert("end");// なにかする
console.log(res);
// Array [ "3000000", "2000000" ]
// resには配列で順番にresolveのリターンが入っている
});
});
function upload() {
return new Promise((resolve, reject) => {
$.ajax({
url:'api1.php',
type:'get'
}).done(function (data) {
alert(data);
resolve(data);
}).fail(function() {
alert("fault");
reject;
});
});
}
function create(response) {
return new Promise((resolve, reject) => {
console.log("create" + response);
$.ajax({
url:'api3.php',
type:'get'
}).done(function (data) {
alert(data);
resolve(data);
}).fail(function() {
alert("fault");
reject;
});
});
}
function edit(response) {
return new Promise((resolve, reject) => {
console.log("edit" + response);
$.ajax({
url:'api2.php',
type:'get'
}).done(function (data) {
alert(data);
resolve(data);
}).fail(function() {
alert("fault");
reject;
});
});
}