2017-09-05 76 views
0

我試圖在多個函數中獲取一些數據,並希望鏈接它們才能在所有數據正確加載時執行最後一個函數。jQuery函數鏈與延遲:.done() - 函數即時調用

問題是,.done()部分中的函數將立即調用,不要等到Deferred-Object解析完成。我也試着用.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)); 
     } 
}