jQuery deferred.promise() 方法
jQuery 雜項(xiàng)方法
實(shí)例
設(shè)定兩個(gè)延時(shí)時(shí)間是隨機(jī)的定時(shí)器,分別用于解決(resolve)和拒絕(reject)延遲對(duì)象
$(function () {
function asyncEvent(){
var dfd = new jQuery.Deferred();
setTimeout(function(){
dfd.resolve("歡呼");
}, Math.floor(400+Math.random()*2000));
setTimeout(function(){
dfd.reject("對(duì)不起");
}, Math.floor(400+Math.random()*2000));
setTimeout(function working(){
if ( dfd.state() === "pending" ) {
dfd.notify("working... ");
setTimeout(working, 500);
}
}, 1);
return dfd.promise();
}
$.when( asyncEvent() ).then(
function(status){
alert( status+', 事情進(jìn)展順利' );
},
function(status){
alert( status+', 這次你失敗了' );
},
function(status){
$("body").append(status);
}
);
})
嘗試一下 ?
定義和用法
deferred.promise() 函數(shù)返回 Deferred(延遲)的 Promise 對(duì)象。
注意:1. 方法允許一個(gè)異步函數(shù)阻止那些干涉其內(nèi)部請(qǐng)求的進(jìn)度(progress)或狀態(tài)(status)的其它代碼。
2. 只包含 deferred 對(duì)象的一組方法,包括:done(),then(),fail(),isResolved(), isRejected(), always(), 這些方法只能觀察一個(gè) deferred 的狀態(tài),而無法更改 deferred 對(duì)象的內(nèi)在狀態(tài)。
3. deferred.promise()也可以接受一個(gè) target 參數(shù),此時(shí)傳入的 target 將被賦予 Promise 的方法,并作為結(jié)果返回,而不是創(chuàng)建一個(gè)新對(duì)象。
語法
deferred.promise( [target ] )
參數(shù) | 描述 |
---|
target | Object類型 綁定 promise 方法的對(duì)象。 |

更多實(shí)例
使用目標(biāo)參數(shù)
使用目標(biāo)參數(shù),促進(jìn)現(xiàn)有對(duì)象的Promise
jQuery 雜項(xiàng)方法
更多建議: