正在将延迟帮助程序转换为TypeScript类



如何将以下js代码从MDN转换为TypeScript类并像new Deferred()一样使用它?

function Deferred() {
// update 062115 for typeof
if (typeof(Promise) != 'undefined' && Promise.defer) {
//need import of Promise.jsm for example: Cu.import('resource:/gree/modules/Promise.jsm');
return Promise.defer();
} else if (typeof(PromiseUtils) != 'undefined'  && PromiseUtils.defer) {
//need import of PromiseUtils.jsm for example: Cu.import('resource:/gree/modules/PromiseUtils.jsm');
return PromiseUtils.defer();
} else {
/* A method to resolve the associated Promise with the value passed.
* If the promise is already settled it does nothing.
*
* @param {anything} value : This value is used to resolve the promise
* If the value is a Promise then the associated promise assumes the state
* of Promise passed as value.
*/
this.resolve = null;
/* A method to reject the assocaited Promise with the value passed.
* If the promise is already settled it does nothing.
*
* @param {anything} reason: The reason for the rejection of the Promise.
* Generally its an Error object. If however a Promise is passed, then the Promise
* itself will be the reason for rejection no matter the state of the Promise.
*/
this.reject = null;
/* A newly created Promise object.
* Initially in pending state.
*/
this.promise = new Promise(function(resolve, reject) {
this.resolve = resolve;
this.reject = reject;
}.bind(this));
Object.freeze(this);
}
}
class Deferred<T = any> {
private _promise: Promise<T>;
private _resolve: (value?: T | PromiseLike<T>) => void;
private _reject: (reason?: any) => void;
constructor() {
this._promise = new Promise<T>((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
get promise() {
return this._promise;
}
resolve(value?: T | PromiseLike<T>) {
this._resolve(value);
}
reject(reason?: any) {
this._reject(reason);
}
}

最新更新