<script type="text/javascript">
/*
Deferred
state (then,done, fail, always,pipe, progress, and state)
change the state (resolve, reject, progress, resolveWith, rejectWith, and progressWith).
deferred 对象一旦被 resolve 或者 reject 之后,状态是不会改变的。
deferred.promise()
The Promise exposes only the Deferred methods needed to attach additional handlers or
determine the state (then, done, fail, always, pipe, progress, state and promise),
but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).
----------------------[pending]
resolve[With]---done [resolved]
reject[With]---fail [rejected]
notify[With]---progress [pending]
---------------then(done,fail,progress),always, pipe--->then
dtd.state():
pending-resolved/rejected
*/
/*
var wait = function(){
var dtd = $.Deferred(); // 新建一个deferred对象
var tasks = function(){
alert("执行完毕!");
dtd.resolve(); // 改变deferred对象的执行状态
};
setTimeout(tasks,5000);
return dtd.promise();
};
$.when( wait())
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出错啦!"); });
*/
var wait = function(dtd){
//var dtd = $.Deferred(); //在函数内部,新建一个Deferred对象
var tasks = function(){
alert("执行完毕!");
dtd.resolve(); // 改变Deferred对象的执行状态
};
setTimeout(tasks,2000);
return dtd.promise(); // 返回promise对象
};
$.Deferred(wait)
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出错啦!"); });
</script>