http://www.cnblogs.com/lvdabao/p/jquery-deferred.html @呂大豹html
var def = $.Deferred(); console.log(def);
function runAsync(){ var def = $.Deferred(); //作一些異步操做 setTimeout(function(){ console.log('執行完成'); def.resolve('隨便什麼數據'); }, 2000); return def; } runAsync().then(function(data){ console.log(data) });
function runAsync(){ var p = new Promise(function(resolve, reject){ //作一些異步操做 setTimeout(function(){ console.log('執行完成'); resolve('隨便什麼數據'); }, 2000); }); return p; } runAsync()
var d = runAsync(); d.then(function(data){ console.log(data) }); d.resolve('在外部結束');
function runAsync(){ var def = $.Deferred(); //作一些異步操做 setTimeout(function(){ console.log('執行完成'); def.resolve('隨便什麼數據'); }, 2000); return def.promise(); //就在這裏調用 }
var d = runAsync(); d.then(function(data){ console.log(data); return runAsync2(); }) .then(function(data){ console.log(data); return runAsync3(); }) .then(function(data){ console.log(data); });
deferred.then( doneFilter [, failFilter ] [, progressFilter ] )
d.then(function(){ console.log('執行完成'); }, function(){ console.log('執行失敗'); });
d.done(function(){ console.log('執行完成'); }) .fail(function(){ console.log('執行失敗'); });
$.when(runAsync(), runAsync2(), runAsync3()) .then(function(data1, data2, data3){ console.log('所有執行完成'); console.log(data1, data2, data3); });
req1 = function(){ return $.ajax(/*...*/); } req2 = function(){ return $.ajax(/*...*/); } req3 = function(){ return $.ajax(/*...*/); } req1().then(req2).then(req3).done(function(){ console.log('請求發送完畢'); });
$.ajax(/*...*/) .success(function(){/*...*/}) .error(function(){/*...*/}) .complete(function(){/*...*/})
deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail;