<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>$.when</title> <script src="http://the5fireblog.b0.upaiyun.com/staticfile/jquery-1.10.2.js"></script> <script> function fn1(){ setTimeout(alert("fn1"),5000); } $.when(fn1()).done(function(){ alert("fn1执行完毕!") }).fail(function(){ alert("出错了!") }) </script> </head> <body> </body> </html>
但是,这样写的话,done()方法会立即执行,起不到回调函数的作用。原因在于$.when()的参数只能是deferred对象,所以必须对wait()进行改写:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>$.when</title> <script src="http://the5fireblog.b0.upaiyun.com/staticfile/jquery-1.10.2.js"></script> <script> /*function fn1(){ setTimeout(alert("fn1"),5000); } $.when(fn1()).done(function(){ alert("fn1执行完毕!") }).fail(function(){ alert("出错了!") })*/ var dtd = $.Deferred();//新建一个Deferred对象 var wait = function(dtd){ var test = function(){ alert("test执行完毕!"); // dtd.resolve();//改变deferred对象的状态 dtd.reject(); } setTimeout(test, 5000); return dtd; } $.when(wait(dtd)).done(function(){ alert("成功!") }).fail(function(){ alert("失败!") }) </script> </head> <body> </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>$.when</title> <script src="http://the5fireblog.b0.upaiyun.com/staticfile/jquery-1.10.2.js"></script> <script> var wait = function(){ var dtd = $.Deferred();//新建一个Deferred对象 var test = function(){ alert("test执行完毕!"); dtd.resolve();//改变deferred对象的状态 // dtd.reject(); } setTimeout(test, 2000); return dtd.promise();//返回promise对象 } // var d = wait(dtd);//新建一个d对象,以为对这个对象进行操作 $.when(wait()).done(function(){ alert("成功!") }).fail(function(){ alert("失败!") }) // dtd.resolve(); // d.resolve();//promise对象不能resolve,这个语句无效 </script> </head> <body> </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>$.when</title> <script src="http://the5fireblog.b0.upaiyun.com/staticfile/jquery-1.10.2.js"></script> <script> var wait = function(){ var test = function(){ alert("test执行完毕!"); } setTimeout(test, 2000); } $.Deferred(wait).done(function(){ alert("成功!") }).fail(function(){ alert("失败!") }) </script> </head> <body> </body> </html>