var d=$.Deferred(); //deferred下面的方法有: // ["resolve", "resolveWith", "reject", "rejectWith", "notify", "notifyWith", // "state", "always", "then", "promise", "pipe", "done", "fail", "progress"] console.info(Object.keys(d)); console.info(d.pipe== d.then);//true console.info(d.state());//初始化pending状态 //------------resolve对应的是done------------ function fn1(){ var def= $.Deferred(); setTimeout(function(){ def.resolve('成功了!'); },1000); return def.promise(); } fn1().done(function(data){ console.info(data);//成功了! }); //或者可以这样写 fn1().then(function(data){ //then的参数为( fnDone, fnFail, fnProgress) console.info(data);//成功了! }); //------------reject对应的是fail------------ function fn2(){ var def= $.Deferred(); setTimeout(function(){ def.reject('失败了!'); },1000); return def.promise(); } fn2().fail(function(data){ console.info(data);//失败了! }); //或者可以这样写 fn2().then(function(data){ //then的参数为( fnDone, fnFail, fnProgress) //不会走 },function(data){ console.info(data); }); //------------notify对应的是progress------------ function fn3(){ var def= $.Deferred(); setTimeout(function(){ def.notify('传递给下一步回调的通知!'); },1000); return def.promise(); } fn3().progress(function(data){ console.info(data);//传递给下一步回调的通知! }); //或者可以这样写 fn3().then(function(data){ //then的参数为( fnDone, fnFail, fnProgress) //不会走 },function(data){ //不会走 },function(data){ console.info(data);//传递给下一步回调的通知! }); //------------always 不管成功与否都会执行回调------------ //deferred.done( arguments ).fail( arguments ); function fn4(){ var def= $.Deferred(); setTimeout(function(){ Math.random()>0.5?def.resolve('成功!'): def.reject('失败!') },1000); return def.promise(); } fn4().always(function(data){ console.info(data);//成功!or失败! }); //------------连续的回调依次执行------------ /*第一异步程序*/ function delayFn1(arg1){ var def= $.Deferred(); setTimeout(function(){ var data=arg1+1; console.info("第一步--->",data); def.resolve(data); },1000); return def.promise(); } /*第二个异步程序*/ function delayFn2(arg2){ var def= $.Deferred(); setTimeout(function(){ var data=arg2+1; def.resolve(data); },1000); return def.promise(); } /*第三个异步程序*/ function delayFn3(arg3){ var def= $.Deferred(); setTimeout(function(){ var data=arg3+1; def.resolve(data); },1000); return def.promise(); } delayFn1(1).then(function(data){ console.info("第二步--->",data); return delayFn2(data) }).then(function(data){ console.info("第三步--->",data); return delayFn3(data) }).then(function(data){ console.info("第四步--->",data); alert(data); })