Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
fix(promise): allow Promise subclassing
Browse files Browse the repository at this point in the history
When loading es6-shim the es6-shim clovers Zone Promise because it does not allow subclassing.
This change now supports subclassing and verifies that constructor throws if invoked on non-Promise subclass.

This change now allows es6-shim to be loaded after Zone.js
  • Loading branch information
mhevery committed Aug 15, 2016
1 parent 6df5f93 commit dafad98
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 4 additions & 1 deletion lib/zone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,9 @@ const Zone: ZoneType = (function(global: any) {
constructor(executor: (resolve : (value?: R | Thenable<R>) => void,
reject: (error?: any) => void) => void) {
const promise: ZoneAwarePromise<R> = this;
if (!(promise instanceof ZoneAwarePromise)) {
throw new Error('Must be an instanceof Promise.');
}
promise[symbolState] = UNRESOLVED;
promise[symbolValue] = []; // queue;
try {
Expand All @@ -1072,7 +1075,7 @@ const Zone: ZoneType = (function(global: any) {
then<R, U>(onFulfilled?: (value: R) => U | Thenable<U>,
onRejected?: (error: any) => U | Thenable<U>): Promise<R>
{
const chainPromise: Promise<R> = new ZoneAwarePromise(null);
const chainPromise: Promise<R> = new (this.constructor as typeof ZoneAwarePromise)(null);
const zone = Zone.current;
if (this[symbolState] == UNRESOLVED ) {
(<any[]>this[symbolValue]).push(zone, chainPromise, onFulfilled, onRejected);
Expand Down
17 changes: 16 additions & 1 deletion test/common/Promise.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,22 @@ describe('Promise', ifEnvSupports('Promise', function () {
it ('should make sure that new Promise is instance of Promise', () => {
expect(Promise.resolve(123) instanceof Promise).toBe(true);
expect(new Promise(() => null) instanceof Promise).toBe(true);
})
});

it('should ensure that Promise this is instanceof Promise', () => {
expect(() => {
Promise.call({}, null);
}).toThrowError('Must be an instanceof Promise.');
});

it('should allow subclassing', () => {
class MyPromise extends Promise<any> {
constructor(fn: any) {
super(fn);
}
}
expect(new MyPromise(null).then(() => null) instanceof MyPromise).toBe(true);
});

it('should intercept scheduling of resolution and then', (done) => {
pZone.run(() => {
Expand Down

0 comments on commit dafad98

Please sign in to comment.