Skip to content

Commit d04dd72

Browse files
robrichardyaacovCR
authored andcommitted
introduce promiseWithResolvers helper (graphql#3902)
Promise.withResolvers is currently a [stage 2 proposal for JS](https://github.com/tc39/proposal-promise-with-resolvers). This adds an equivalent jsutil to standardize usage.
1 parent a67f659 commit d04dd72

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { expect } from 'chai';
2+
import { describe, it } from 'mocha';
3+
4+
import { expectPromise } from '../../__testUtils__/expectPromise.js';
5+
6+
import { promiseWithResolvers } from '../promiseWithResolvers.js';
7+
8+
describe('promiseWithResolvers', () => {
9+
it('resolves values', async () => {
10+
const { promise, resolve } = promiseWithResolvers();
11+
resolve('foo');
12+
expect(await expectPromise(promise).toResolve()).to.equal('foo');
13+
});
14+
15+
it('rejects values', async () => {
16+
const { promise, reject } = promiseWithResolvers();
17+
const error = new Error('rejected');
18+
reject(error);
19+
await expectPromise(promise).toRejectWith('rejected');
20+
});
21+
});
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import type { PromiseOrValue } from './PromiseOrValue.js';
2+
3+
/**
4+
* Based on Promise.withResolvers proposal
5+
* https://github.com/tc39/proposal-promise-with-resolvers
6+
*/
7+
export function promiseWithResolvers<T>(): {
8+
promise: Promise<T>;
9+
resolve: (value: T | PromiseOrValue<T>) => void;
10+
reject: (reason?: any) => void;
11+
} {
12+
// these are assigned synchronously within the Promise constructor
13+
let resolve!: (value: T | PromiseOrValue<T>) => void;
14+
let reject!: (reason?: any) => void;
15+
const promise = new Promise<T>((res, rej) => {
16+
resolve = res;
17+
reject = rej;
18+
});
19+
return { promise, resolve, reject };
20+
}

0 commit comments

Comments
 (0)