标签:
http://www.cnblogs.com/lvdabao/p/jquery-deferred.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;
大白话讲解Promise(三)搞懂jquery中的Promise
标签:
原文地址:http://www.cnblogs.com/Andy692126/p/5379055.html