X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=shared%2Fcore-utils%2Fcommon%2Fpromises.ts;h=f17221b97fb61841f7aeeb86c1d2cd4f6b9b4341;hb=841cb202432a2abf538465f69953027973dc02aa;hp=7ef9d60b6a80948e0cbc5ebd4554961d547265c5;hpb=9e8789497377cac5554a622da605f5b89587aa9c;p=github%2FChocobozzz%2FPeerTube.git diff --git a/shared/core-utils/common/promises.ts b/shared/core-utils/common/promises.ts index 7ef9d60b6..f17221b97 100644 --- a/shared/core-utils/common/promises.ts +++ b/shared/core-utils/common/promises.ts @@ -1,12 +1,25 @@ -function isPromise (value: any) { - return value && typeof value.then === 'function' +function isPromise (value: T | Promise): value is Promise { + return value && typeof (value as Promise).then === 'function' } function isCatchable (value: any) { return value && typeof value.catch === 'function' } +function timeoutPromise (promise: Promise, timeoutMs: number) { + let timer: ReturnType + + return Promise.race([ + promise, + + new Promise((_res, rej) => { + timer = setTimeout(() => rej(new Error('Timeout')), timeoutMs) + }) + ]).finally(() => clearTimeout(timer)) +} + export { isPromise, - isCatchable + isCatchable, + timeoutPromise }