addons/shared/rejectAfterTimeout.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318/**
b69ab319 * Takes an existing Promise and wraps it with a new Promise that will either:
b69ab3110 * - be fulfilled with the result from the original promise
b69ab3111 * - be rejected with the provided error message after `timeoutInMillis`
b69ab3112 * milliseconds.
b69ab3113 *
b69ab3114 * Note that in the case where the returned Promise rejects, there is nothing
b69ab3115 * that stops the execution of the executor function used to create the
b69ab3116 * original Promise.
b69ab3117 */
b69ab3118export default function rejectAfterTimeout<T>(
b69ab3119 promise: Promise<T>,
b69ab3120 timeoutInMillis: number,
b69ab3121 message: string,
b69ab3122): Promise<T> {
b69ab3123 return Promise.race([
b69ab3124 promise,
b69ab3125 new Promise<T>((_resolve, reject) => {
b69ab3126 setTimeout(() => reject(message), timeoutInMillis);
b69ab3127 }),
b69ab3128 ]);
b69ab3129}