aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/core-utils/common/promises.ts
blob: f17221b97fb61841f7aeeb86c1d2cd4f6b9b4341 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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,
  timeoutPromise
}