Skip to content

Commit

Permalink
Use Promise.withResolvers to simplify promise handling (#11666)
Browse files Browse the repository at this point in the history
* Use Promise.withResolvers to simplify promise handling

changelog: Internal, Code Quality, Simplify code using newly-available JavaScript features

* Pass dummy error object to rejected promise
  • Loading branch information
aduth authored Dec 18, 2024
1 parent 870e1d8 commit 5e546a4
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,7 @@ import { pathToFileURL } from 'node:url';

describe('digital analytics program', () => {
it('parses without syntax error', async () => {
// Future: Replace with Promise.withResolvers once supported
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
let resolve;
const promise = new Promise((_resolve) => {
resolve = _resolve;
});
const { promise, resolve } = Promise.withResolvers<void>();

// Reference: https://github.com/nodejs/node/issues/30682
const toDataURL = (source: string) =>
Expand Down
32 changes: 5 additions & 27 deletions spec/javascript/packages/document-capture/hooks/use-async-spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,8 @@ describe('document-capture/hooks/use-async', () => {
}

it('returns suspense resource that renders fallback', async () => {
let resolve;
const createPromise = sinon
.stub()
.onCall(0)
.returns(
new Promise((_resolve) => {
resolve = () => {
_resolve();
};
}),
)
.onCall(1)
.throws();
const { promise, resolve } = Promise.withResolvers();
const createPromise = sinon.stub().onCall(0).returns(promise).onCall(1).throws();

const { container, findByText } = render(<Parent createPromise={createPromise} />);

Expand All @@ -47,25 +36,14 @@ describe('document-capture/hooks/use-async', () => {
});

it('returns suspense resource that renders error fallback', async () => {
let reject;
const createPromise = sinon
.stub()
.onCall(0)
.returns(
new Promise((_resolve, _reject) => {
reject = () => {
_reject(new Error());
};
}),
)
.onCall(1)
.throws();
const { promise, reject } = Promise.withResolvers();
const createPromise = sinon.stub().onCall(0).returns(promise).onCall(1).throws();

const { container, findByText } = render(<Parent createPromise={createPromise} />);

expect(container.textContent).to.equal('Loading');

reject();
reject(new Error());

expect(await findByText('Error')).to.be.ok();
expect(console).to.have.loggedError();
Expand Down

0 comments on commit 5e546a4

Please sign in to comment.