Latest web development tutorials

jQuery deferred.promise() 方法

jQuery 雜項方法 jQuery雜項方法

實例

設定兩個延時時間是隨機的定時器,分別用於解決(resolve)和拒絕(reject)延遲對象

$ ( function ( ) { function asyncEvent ( ) { var dfd = new jQuery . Deferred ( ) ; // 在一個隨機的時間間隔之後Resolve (解決狀態) setTimeout ( function ( ) { dfd . resolve ( " 歡呼 " ) ; } , Math . floor ( 400 + Math . random ( ) * 2000 ) ) ; // 在一個隨機的時間間隔之後reject (拒絕狀態) setTimeout ( function ( ) { dfd . reject ( " 對不起 " ) ; } , Math . floor ( 400 + Math . random ( ) * 2000 ) ) ; // 每半秒顯示一個"working..."消息 setTimeout ( function working ( ) { if ( dfd . state ( ) === " pending " ) { dfd . notify ( " working... " ) ; setTimeout ( working , 500 ) ; } } , 1 ) ; // 返回Promise對象,調用者不能改變延遲對象 return dfd . promise ( ) ; } // 為異步函數附加一個done, fail,和progress處理程序 $. when ( asyncEvent ( ) ) . then ( function ( status ) { alert ( status + ' ,事情進展順利 ' ) ; } , function ( status ) { alert ( status + ' ,這次你失敗了 ' ) ; } , function ( status ) { $ ( " body " ) . append ( status ) ; } ) ; } )

嘗試一下»

定義和用法

deferred.promise() 函數返回Deferred(延遲)的Promise 對象。

注意: 1.方法允許一個異步函數阻止那些干涉其內部請求的進度(progress)或狀態(status)的其它代碼。
2. 只包含deferred 對象的一組方法,包括:done(),then(),fail(),isResolved(), isRejected(), always(), 這些方法只能觀察一個deferred 的狀態,而無法更改deferred 對象的內在狀態。
3. deferred.promise()也可以接受一個target 參數,此時傳入的target 將被賦予Promise 的方法,並作為結果返回,而不是創建一個新對象。


語法

deferred.promise( [target ] )

参数 描述
target Object类型 绑定 promise 方法的对象。


實例

更多實例

使用目標參數
使用目標參數,促進現有對象的Promise


jQuery 雜項方法 jQuery雜項方法