2016-06-16 8 views
0

3 건의 아약스 요청을 실행해야합니다. 나는 그것들이 기본적으로 비동기가된다는 것을 안다. (그래서 VM을 동기식으로 만들어 버린다. 그런 식으로하고 싶지 않다.) 내가하는 일은 변수를 3 번 ​​전달하는 함수를 호출하는 것이다.Javascript에서 재귀 콜백을 시퀀싱하는 방법은 무엇입니까?

그러나 지금보기()는 결과가 조리되지 않으면 즉시 트리거됩니다. 어떻게하면 다른 것들을 하나씩 발생 시키도록 설정할 수 있습니까? 나는 콜백에 대해서 읽었지 만 3 가지 기능이 없기 때문에 혼란 스럽지만 다른 변수를 취하는 것은 매우 혼란 스럽다.

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 
} 
+1

약속을 살펴보십시오. 콜백 지옥을 탐구 할 필요없이 시퀀스 된 콜백을 수행 할 수있는보다 관리하기 쉬운 방법입니다. – zero298

답변

1

와 함수를 사용에서 -

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 
} 
+0

감사 빌리! 나는 약속을 철저히 지키겠다. 나는 JS를 배우는 중이고 콜백은 이미 협박하고있다. 다시 링크를 가져 주셔서 감사합니다. – Ashtrix

0

당신은 이런 식으로 일을 시도 할 수 있습니다 : 당신의 아약스 전화를 만들기 위해 당신은 배열에 변수를 저장할 수 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); 

}); 
관련 문제