Skip to content

Instantly share code, notes, and snippets.

@rebornix
Created August 4, 2015 07:02
Show Gist options
  • Save rebornix/e390b3be863f328c8ddf to your computer and use it in GitHub Desktop.
Save rebornix/e390b3be863f328c8ddf to your computer and use it in GitHub Desktop.
Angular $q written in typescript (draft)
interface PromiseState {
status: number;
}
class Promise {
$$state: PromiseState;
constructor() {
this.$$state = { status : 0 };
}
then(onFulfilled, onRejected, progressBack) {
var result = new Deferred();
this.$$state.pending = this.$$state.pending || [];
this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
return result.promise;
}
catch(callback) {
return this.then(null, callback);
}
finally(callback, progressBack) {
return this.then(function(value) {
return handleCallback(value, true, callback);
}, function(error) {
return handleCallback(error, false, callback);
}, progressBack);
}
}
}
class Deferred {
promise: Promise;
constructor() {
this.promise = new Promise();
}
resolve(val) {
if (this.promise.$$state.status)
return;
if (val === this.promise) {
this.$$reject($qMinErr(
'qcycle',
"Expected promise to be resolved with value other than itself '{0}'",
val));
}
else
{
var then, fns;
fns = callOnce(this, this.$$resolve, this.$$reject);
try {
if ((isObject(val) || isFunction(val)))
then = val && val.then;
if (isFunction(then))
{
this.promise.$$state.status = -1;
then.call(val, fns[0], fns[1], this.notify);
}
else
{
this.promise.$$state.value = val;
this.promise.$$state.status = 1;
scheduleProcessQueue(this.promise.$$state);
}
}
catch (e)
{
fns[1](e);
}
exceptionHandler(e);
}
}
reject(reason) {
if (this.promise.$$state.status)
return;
this.promise.$$state.value = reason;
this.promise.$$state.status = 2;
scheduleProcessQueue(this.promise.$$state);
}
notify(progress) {
var callbacks = this.promise.$$state.pending;
if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
nextTick(function() {
var callback, result;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
result = callbacks[i][0];
callback = callbacks[i][3];
try {
result.notify(isFunction(callback) ? callback(progress) : progress);
} catch (e) {
exceptionHandler(e);
}
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment