This project is read-only.

jQuery Promise result type

Topics: General, Language Specification
Oct 4, 2012 at 7:04 PM

I use the jQuery deferred object very often to create custom async promises in my application, ajax api calls, timers, animations, etc.

I'd like to emphasize the need for generic types here. I want to be able to create a Deferred object that is restricted to resolve the result with a specific type, and also a promise object that gives a known type on done.

For example something like this:

function SomeAsyncOperation() : JQueryPromise<number>
	var result = $.Deferred();
	setTimeout(function () { 
	}, 1000);
	return result.promise<number>();

	.done(function (result) {  
		// result should be a number here

What do you think? Will this be possible? It would be really useful.

Oct 4, 2012 at 7:20 PM

Generics are an active discussion topic right now. We're collecting motivating examples to help the design, so having examples like yours is very helpful. 

Thanks for the feedback. 

Oct 4, 2012 at 8:45 PM

I thought I'd to this what I've done to strongly type promises using interfaces.  What I did was define basic a basic Promise & Deferred interface and then to strongly type things I derive a strongly typed Promise from the basic one and override the methods I need to type. Then you just have your code reference the strongly typed promises.  It's no substitute for generics but it works (at least currently.) 

// Define basic Promise & Deferred interfaces

interface IPromise {
		done (onDone: () => any): IPromise;
		fail (onFail: () => any): IPromise;
		progress (onProgress: () => any): IPromise;
		state (): string;
		then (onDone: () => any, onFail: () => any, onProgress?: () => any): IPromise;

interface IDeferred extends IPromise {
	notify (...args:any[]): void;
	notifyWith (context, args?: any[]): void;

	promise (): IPromise;

	reject (...args:any[]): void;
	rejectWith (context, args?: any[]): void;

	resolve (...args:any[]): void;
	resolveWith (context, args?: any[]): void;

// Strongly type the Promise

interface IStringResult extends IPromise {
	done (onDone: (value:string) => any): IStringResult;
	fail (onFail: (error: string) => any): IStringResult;
	progress (onProgress: (value:string) => any): IStringResult;
	then (onDone: (value:string) => any, onFail: (error: string) => any, onProgress?: (value:string) => any): IStringResult;

var x:IStringResult;
x.done((value) => {





May 29, 2013 at 2:42 AM
Is there a recommended way or an example of how to do this now with the generics support added to 0.9?
May 31, 2013 at 8:55 AM
ctaggart wrote:
Is there a recommended way or an example of how to do this now with the generics support added to 0.9?
Take a look at this: