Skip to content

Commit 4190028

Browse files
author
Juarez Mota
committed
fix: optimize message picking with Promise.allSettled
1 parent ec85f7c commit 4190028

File tree

1 file changed

+27
-18
lines changed

1 file changed

+27
-18
lines changed

dotcom-rendering/src/lib/messagePicker.ts

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -155,25 +155,34 @@ export async function pickMessage(
155155
);
156156

157157
try {
158-
for (const config of candidateConfigsWithTimeout) {
159-
try {
160-
const result = await config.candidate.canShow();
161-
config.cancelTimeout();
162-
163-
if (result.show) {
164-
clearAllTimeouts(candidateConfigsWithTimeout);
165-
const { candidate } = config;
166-
return () => candidate.show(result.meta);
167-
}
168-
} catch (error) {
169-
if (error instanceof Error) {
170-
window.guardian.modules.sentry.reportError(
171-
error,
172-
`pickMessage: error checking ${config.candidate.id}`,
173-
);
174-
}
158+
const settled = await Promise.allSettled(
159+
candidateConfigsWithTimeout.map((config) =>
160+
config.candidate.canShow(),
161+
),
162+
);
163+
164+
for (let i = 0; i < candidateConfigsWithTimeout.length; i++) {
165+
const config = candidateConfigsWithTimeout[i];
166+
const result = settled[i];
167+
168+
config?.cancelTimeout();
169+
170+
if (
171+
result?.status === 'rejected' &&
172+
result.reason instanceof Error
173+
) {
174+
window.guardian.modules.sentry.reportError(
175+
result.reason,
176+
`pickMessage: error checking ${config?.candidate.id}`,
177+
);
178+
continue;
179+
}
175180

176-
config.cancelTimeout();
181+
const canShowResult =
182+
result?.status === 'fulfilled' ? result.value : undefined;
183+
if (canShowResult?.show) {
184+
clearAllTimeouts(candidateConfigsWithTimeout);
185+
return () => config?.candidate.show(canShowResult.meta) ?? null;
177186
}
178187
}
179188

0 commit comments

Comments
 (0)