Reviewed By: danielbuechele Differential Revision: D16710520 fbshipit-source-id: 146ec33537de038d59e6f13647ee0de7b9edbcb8
24 lines
683 B
TypeScript
24 lines
683 B
TypeScript
/**
|
|
* Copyright 2018-present Facebook.
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
* @format
|
|
*/
|
|
|
|
export default function promiseTimeout<T>(
|
|
ms: number,
|
|
promise: Promise<T>,
|
|
timeoutMessage?: string,
|
|
): Promise<T> {
|
|
// Create a promise that rejects in <ms> milliseconds
|
|
const timeout: Promise<T> = new Promise((resolve, reject) => {
|
|
const id = setTimeout(() => {
|
|
clearTimeout(id);
|
|
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]);
|
|
}
|