Deferred.promise Method (object)

Return a Deferred's Promise object.

Namespace: SharpKit.jQuery

Class: Deferred


public Promise promise(object target)


Type: System.Object
targetObject onto which the promise methods have to be attached

Return Value

Type: SharpKit.jQuery.Promise
Returns: Promise


Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action.
//Create a Deferred and return its Promise
function asyncEvent(){var dfd = new jQuery.Deferred();setTimeout(function(){dfd.resolve("hurray");}, Math.floor(Math.random()*1500));setTimeout(function(){dfd.reject("sorry");}, Math.floor(Math.random()*1500));return dfd.promise();}
// Attach a done and fail handler for the asyncEvent
$.when( asyncEvent() ).then(function(status){alert( status+', things are going well' );},function(status){alert( status+', you fail this time' );});
Use the target argument to promote an existing object to a Promise:
//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"
© Copyright 2005-2011 SharpKit. All rights reserved.