891 B30 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8/**
9 * Takes an existing Promise and wraps it with a new Promise that will either:
10 * - be fulfilled with the result from the original promise
11 * - be rejected with the provided error message after `timeoutInMillis`
12 * milliseconds.
13 *
14 * Note that in the case where the returned Promise rejects, there is nothing
15 * that stops the execution of the executor function used to create the
16 * original Promise.
17 */
18export default function rejectAfterTimeout<T>(
19 promise: Promise<T>,
20 timeoutInMillis: number,
21 message: string,
22): Promise<T> {
23 return Promise.race([
24 promise,
25 new Promise<T>((_resolve, reject) => {
26 setTimeout(() => reject(message), timeoutInMillis);
27 }),
28 ]);
29}
30