Don't create always rejecting promises for timeout
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
This commit is contained in:
committed by
Facebook GitHub Bot
parent
704e14a91a
commit
e4a3696fd5
@@ -7,18 +7,21 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
import {sleep} from './sleep';
|
||||
|
||||
export function timeout<T>(
|
||||
ms: number,
|
||||
promise: Promise<T>,
|
||||
timeoutMessage?: string,
|
||||
): Promise<T> {
|
||||
// Create a promise that rejects in <ms> milliseconds
|
||||
const timeout = sleep(ms).then(() => {
|
||||
throw new Error(timeoutMessage || `Timed out in ${ms} ms.`);
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeoutHandle = setTimeout(() => {
|
||||
reject(new Error(timeoutMessage || `Timed out in ${ms} ms.`));
|
||||
}, ms);
|
||||
|
||||
// Returns a race between our timeout and the passed in promise
|
||||
return Promise.race([promise, timeout]);
|
||||
promise
|
||||
.then(resolve)
|
||||
.finally(() => {
|
||||
clearTimeout(timeoutHandle);
|
||||
})
|
||||
.catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user