LoginSignup
0
0

More than 1 year has passed since last update.

複数のpromiseをまとめて実行して、処理が終わってからなにかする

Posted at

どうも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;
        });
    });
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0