Summary: Our existing `timeout` implementation was always throwing an exception, due to sleeping and then throw an exception, which is than handled but ignored by `Promise.race`. This implementation has a few problems 1. Because it always throws, having a debugger session with 'break on caught exceptions' will pause on every usage of timeout (rather than just the ones that actually timeout). This makes this way of debugging a bit useless. 2. Throwing exceptions is in principle an expensive process (due to the stack trace generation) 3. Not cancelling the timeout used by sleep is a bit of a waste as well Reviewed By: lawrencelomax Differential Revision: D33982717 fbshipit-source-id: d739c02112e1c1bc4cd691af852371d08a99abc6
28 lines
617 B
TypeScript
28 lines
617 B
TypeScript
/**
|
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*
|
|
* @format
|
|
*/
|
|
|
|
export function timeout<T>(
|
|
ms: number,
|
|
promise: Promise<T>,
|
|
timeoutMessage?: string,
|
|
): Promise<T> {
|
|
return new Promise((resolve, reject) => {
|
|
const timeoutHandle = setTimeout(() => {
|
|
reject(new Error(timeoutMessage || `Timed out in ${ms} ms.`));
|
|
}, ms);
|
|
|
|
promise
|
|
.then(resolve)
|
|
.finally(() => {
|
|
clearTimeout(timeoutHandle);
|
|
})
|
|
.catch(reject);
|
|
});
|
|
}
|