以下内容摘自jQuery Api 1.7
function asyncEvent() { var dfd = new jQuery.Deferred(); // Resolve after a random interval setTimeout(function () { dfd.resolve("hurray"); //触发成功事件 | 被done注册的函数 }, Math.floor(400 + Math.random() * 2000)); // Reject after a random interval setTimeout(function () { dfd.reject("sorry"); //触发失败事件 | 被fail注册的函数 }, Math.floor(400 + Math.random() * 2000)); // Show a "working..." message every half-second setTimeout(function working() { if (dfd.state() === "pending") { dfd.notify("working... "); //触发progress事件 setTimeout(working, 500); } }, 1);//精彩的代码 // Return the Promise so caller can't change the Deferred return dfd.promise(); //删掉用于触发的方法:reject,resolve,notify } asyncEvent().done(function () { console.log('成功'); }).fail(function () { console.log('失败'); }).always(function () { console.log('不管成败,反正是结束了'); }).progress(function () { console.log('you got a message~'); });
还有一些方便使用的函数:$.when(dfd1,[dfd2,[dfd3]]),他返回的还是Deferrd对象。当传入的所有dfd都成功后,才会触发done事件。当任意一个dfd失败,立即触发fail
var a=$.Deferred(); var b=$.Deferred(); $.when(a,b) .fail(function(){console.log('失败');}) .done(function(){console.log('成功');}); b.resolve() a.resolve() //输出:成功
var a=$.Deferred(); var b=$.Deferred(); $.when(a,b) .fail(function(){console.log('失败');}) .done(function(){console.log('成功');}); b.reject() //输出:失败
then是一个快捷方法:dfd.then(doneCallback,failCallback,[progressCallback]);
还有:在所有的触发用方法都可以传递一个参数
// Attach a done, fail, and progress handler for the asyncEvent $.when(asyncEvent()).then(function (status) { //注册成功回调,done console.log(status + ', things are going well'); }, function (status) { //注册失败回调,fail console.log(status + ', you fail this time'); }, function (status) { //注册progress回调。1.7新增 $("body").append(status); });
最后说精彩的代码: http://p2world.iteye.com/blog/1405227
http://p2world.iteye.com/blog/1405238