2016-08-03 40 views
0

我有這個事件的按鈕:使用延遲jQuery的非同步POST調用

$("#getSensorsObs").click(function (e) { 
     e.preventDefault(); 
     postCallOne(); 
     postCallTwo(); 
    }); 

我想postCallTwo火的時候postCallOne已成功完成了第一個電話。

function postCallOne() { 
    setWait(); 
    //do something 

    return $.post(ADDRESS, {fieldONE : fieldOneVal }) 
    .done(function (data) { 
     console.log("RESPONSE SUCCESS "); 
     // do something 

    }).error(function(x, t, m) { 
      alert(x + ' ' + t + ' ' + m); 
     } 
    }).then(function (resp) { 
     return $.Deferred(function(def){ 
     def.resolveWith({},[resp == 1,valueSelected]); 
    }).promise(); 
}); 

這是第二個功能:

function postCallTwo() { 
    setWait(); 
    //do something 

    return $.post(ADDRESS2, {fieldONE : fieldOneVal }) 
    .done(function (data) { 
     console.log("RESPONSE SUCCESS "); 
     // do something 

    }).error(function(x, t, m) { 
      alert(x + ' ' + t + ' ' + m); 
     } 
    }); 
}); 

我有嘗試:

$("#button").click(function (e) { 
     e.preventDefault(); 
     postCallOne.then(function(){postCallTwo();}); 

    }); 

但我已經回到postCallOne.done不是一個函數。

我不太清楚延期,誰能幫幫我?

非常感謝。

+0

'postCallOne()。done(postCallTwo);'?! –

回答

1

你需要調用它像這樣:

$("#button").click(function (e) { 
    e.preventDefault(); 
    postCallOne().then(function() {postCallTwo()};); 

}); 

與你所寫的方法的問題是之前的延遲從postCallOne解決呼叫postCallTwo將被放置。您需要等待postCallOne解決,然後您將postCallTwo鏈接到postCallOne的成功。這就是延期存在的原因。

+0

但我已經返回Uncaught TypeError:postCallOne.done不是函數 – michele

+0

我的不好,請使用鏈接它.then:'postCallOne.then(function(){postCallTwo()})' – Araknid

+0

mmmm現在我有.then函數 – michele