2017-09-05 4 views
0

여러 함수에서 일부 데이터를 얻으 려하고 모든 데이터가 제대로로드 된 경우에만 마지막 함수를 실행하기 위해 체인을 연결하려고합니다.jQuery 함수 체이닝 with 지연 : .done() - 즉각적으로 호출되는 함수

.done() 부분의 함수는 즉시 호출되고 지연된 개체가 해결 될 때까지 대기하지 않는 것이 문제입니다. 나는 또한 .then()로 묶어서 시도했지만 이것도 작동하지 않았다.

var array1, array2; 

function doStuffWithReceivedData() { 
    // Working with the data 
} 

function getArray1() { 
    var defArray1 = $.Deferred(); 

    $.getJSON(url, function(data) { 
     if (data.success) { 
      array1 = data.payload; 
      defArray1.resolve(); 
     } else { 
      // Information displayed that there was an error 
     } 
    }) 

    return defArray1; 
} 

// Function 2 is like the first one 
function getArray2() {...}; 

$(document).read(function() { 
    getArray1() 
     .done(getArray2() 
      .done(doStuffWithReceivedData())); 
} 
+2

당신은 참조를 제공하지 않고 이러한 메서드를 호출하고 있습니다. 괄호를 제거하십시오. –

+0

this - getArray1(). promise(). done (function() { doStuffWithReceivedData() }); –

+0

https://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference – Utkanos

답변

1

.done()의 인수는 함수 여야합니다. 함수를 호출하고 있습니다. 전달하지 않습니다. 괄호를 벗어 버려라.

$(document).ready(function() { 
    getArray1() 
     .done(function() { 
      getArray2().done(doStuffWithReceivedData)); 
     } 
}