deferred.promise()
deferred.promise( [target] ) 1.5追加
戻り値:Promise
Deferredのpromiseオブジェクトを返します。
引数 | 説明 |
---|---|
target | promiseメソッドに付属させたいオブジェクトを指定します。 |
function asyncEvent(){
var dfd = new jQuery.Deferred();
// Resolve after a random interval
setTimeout(function(){
dfd.resolve("hurray");
}, Math.floor(400+Math.random()*2000));
// Reject after a random interval
setTimeout(function(){
dfd.reject("sorry");
}, Math.floor(400+Math.random()*2000));
// Show a "working..." message every half-second
setTimeout(function working(){
if ( dfd.state() === "pending" ) {
dfd.notify("working... ");
setTimeout(working, 500);
}
}, 1);
// Return the Promise so caller can't change the Deferred
return dfd.promise();
}
// Attach a done, fail, and progress handler for the asyncEvent
$.when( asyncEvent() ).then(
function(status){
alert( status+', things are going well' );
},
function(status){
alert( status+', you fail this time' );
},
function(status){
$("body").append(status);
}
);
// Existing object
var obj = {
hello: function( name ) {
alert( "Hello " + name );
}
},
// Create a Deferred
defer = $.Deferred();
// Set object as a promise
defer.promise( obj );
// Resolve the deferred
defer.resolve( "John" );
// Use the object as a Promise
obj.done(function( name ) {
obj.hello( name ); // will alert "Hello John"
}).hello( "Karl" ); // will alert "Hello Karl"
© 2010 - 2017 STUDIO KINGDOM