@xylabs/sdk-js 2.4.2 → 2.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/forget.ts CHANGED
@@ -1,12 +1,45 @@
1
+ import { delay } from './delay'
2
+
3
+ interface ForgetTimeoutConfig {
4
+ delay: number
5
+ cancel: () => void
6
+ }
7
+
1
8
  //used to explicitly launch an async funtion (or Promise) with awaiting it
2
- const forget = (promise?: Promise<unknown>) => {
3
- promise
4
- ?.then(() => {
9
+ export const forget = (promise: Promise<unknown>, timeout?: ForgetTimeoutConfig) => {
10
+ let completed = false
11
+
12
+ const promiseWrapper = async () => {
13
+ await promise
14
+ .then(() => {
15
+ completed = true
16
+ })
17
+ .catch(() => {
18
+ completed = true
19
+ })
20
+ }
21
+
22
+ const promises = [promiseWrapper()]
23
+
24
+ //if there is a timeout, add it to the race
25
+ if (timeout) {
26
+ const timeoutFunc = async () => {
27
+ await delay(timeout.delay)
28
+ if (!completed) {
29
+ console.log(`forget promise timeout out after ${timeout.delay}ms [Cancelling]`)
30
+ timeout.cancel?.()
31
+ }
32
+ }
33
+ promises.push(timeoutFunc())
34
+ }
35
+
36
+ const all = Promise.race(promises)
37
+
38
+ all
39
+ .then(() => {
5
40
  return
6
41
  })
7
42
  .catch(() => {
8
43
  return
9
44
  })
10
45
  }
11
-
12
- export { forget }