]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - shared/core-utils/common/promises.ts
Type isPromise
[github/Chocobozzz/PeerTube.git] / shared / core-utils / common / promises.ts
index 7ef9d60b6a80948e0cbc5ebd4554961d547265c5..f17221b97fb61841f7aeeb86c1d2cd4f6b9b4341 100644 (file)
@@ -1,12 +1,25 @@
-function isPromise (value: any) {
-  return value && typeof value.then === 'function'
+function isPromise <T = unknown> (value: T | Promise<T>): value is Promise<T> {
+  return value && typeof (value as Promise<T>).then === 'function'
 }
 
 function isCatchable (value: any) {
   return value && typeof value.catch === 'function'
 }
 
+function timeoutPromise <T> (promise: Promise<T>, timeoutMs: number) {
+  let timer: ReturnType<typeof setTimeout>
+
+  return Promise.race([
+    promise,
+
+    new Promise((_res, rej) => {
+      timer = setTimeout(() => rej(new Error('Timeout')), timeoutMs)
+    })
+  ]).finally(() => clearTimeout(timer))
+}
+
 export {
   isPromise,
-  isCatchable
+  isCatchable,
+  timeoutPromise
 }