2016-06-16 4 views
0

3つのajaxリクエストを実行する必要があります。私はそれらがデフォルトでは非同期になることを知っています(VMを同期させてしまうので、私はそうしたくありません)。私がやる方法は、変数を3回渡すという関数を呼び出すことです。Javascriptで再帰的コールバックをシーケンスする方法は?

しかし、現在は、結果が料理されていないときにview()がトリガーされます。どのように私はそれらを次々に起こるように設定しますか?私はコールバックについて読んでいますが、私は3つの異なる機能を持っているのではなく、異なる変数をとっているだけなので、非常に混乱しています。

+1

約束を見てください。彼らはコールバック地獄を掘り下げることなく、順序付けされたコールバックを行うために、よりメンテナンス可能な方法です。 – zero298

答えて

1

var variables = [var1, var2, var3]; 

function callParse() { 
    if(variables.length) { 
    var currentVar = variables.shift(); 
    parse(currentVar); 
    } 
    else { 
    view(); 
    } 
} 

function parse(variable){ 
    //ajax request here 
    $.ajax({ 
    type:"POST", 
    url:'script.php', 
    data:{variable:variable}, 
    success:function(data) 
    { 
     result+=data; 
     callParse(); 
    } 
    }); 
} 

function view(){ 
//do something with result 
} 
0

チェーンの約束を試してください - :あなたは配列にあなたの変数を格納し、あなたのAJAX呼び出しを行うために機能を使用することができhttps://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/

$.when(
    // Get the HTML 
    $.get("/feature/", function(html) { 
    globalStore.html = html; 
    }), 

    // Get the CSS 
    $.get("/assets/feature.css", function(css) { 
    globalStore.css = css; 
    }), 

    // Get the JS 
    $.getScript("/assets/feature.js") 

).then(function() { 

    // All is ready now, so... 

    // Add CSS to page 
    $("<style />").html(globalStore.css).appendTo("head"); 

    // Add HTML to page 
    $("body").append(globalStore.html); 

}); 
+0

ありがとうビリー!私は徹底的に約束を貫きます。私はJSを学んでいるだけで、コールバックはすでに脅迫しています。もう一度リンクをありがとう。 – Ashtrix

0

あなたはこのようにそれをやってみてください:

parseAndView([var1, var2, var3]); 

function parseAndView(vars, index) { 
    index = index || 0; //initialize index if not passed 

    //execute the AJAX call only if there are more variables to parse 
    if (index < vars.length) 
     //ajax request here 
     $.ajax({ 
      type: "POST", 
      url: 'script.php', 
      data: {variable: vars[index]}, 
      success: function (data) { 
       // result stored in a global variable 
       result += data; 
       // recursive call to parse another variable 
       parseAndView(vars, index++); 
      } 
     }); 
    else 
     view(); 
} 

function view() { 
    //do something with result 
} 
関連する問題