Skip to content

Commit

Permalink
feat(zone.js): implement Promise.withResolvers() (#53514)
Browse files Browse the repository at this point in the history
Implement `Promise.withResolvers()`

```
const {promise, resolve, reject} = Promise.withResolvers();
```

PR Close #53514
  • Loading branch information
JiaLiPassion authored and alxhub committed Dec 12, 2023
1 parent cc02852 commit 7a28f50
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/zone.js/lib/common/promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,19 @@ Zone.__load_patch('ZoneAwarePromise', (global: any, Zone: ZoneType, api: _ZonePr
return resolvePromise(<ZoneAwarePromise<U>>new this(null as any), REJECTED, error);
}

static withResolvers<T>(): {
promise: Promise<T>,
resolve: (value?: T|PromiseLike<T>) => void,
reject: (error?: any) => void
} {
const result: any = {};
result.promise = new ZoneAwarePromise((res, rej) => {
result.resolve = res;
result.reject = rej;
});
return result;
}

static any<T>(values: Iterable<PromiseLike<T>>): Promise<T> {
if (!values || typeof values[Symbol.iterator] !== 'function') {
return Promise.reject(new AggregateError([], 'All promises were rejected'));
Expand Down
20 changes: 20 additions & 0 deletions packages/zone.js/test/common/Promise.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -911,4 +911,24 @@ describe(
});
});
});

describe('Promise.withResolvers', () => {
it('should resolve', (done: DoneFn) => {
const {promise, resolve, reject} = (Promise as any).withResolvers();
promise.then((v: any) => {
expect(v).toBe(1);
done();
});
resolve(1);
});
it('should reject', (done: DoneFn) => {
const {promise, resolve, reject} = (Promise as any).withResolvers();
const error = new Error('test');
promise.catch((e: any) => {
expect(e).toBe(error);
done();
});
reject(error);
});
});
}));

0 comments on commit 7a28f50

Please sign in to comment.