import { flow } from "../Function"; import type { AsyncExit } from "./AsyncExit"; import { failure, success } from "./AsyncExit"; import { succeed, unfailable } from "./constructors"; import { foldM_ } from "./fold"; import type { Async } from "./model"; import { FinalizeInstruction } from "./model"; import { chain_ } from "./monad"; export const sleep = (ms: number): Async => unfailable( (onInterrupt) => new Promise((resolve) => { const timer = setTimeout(() => { resolve(undefined); }, ms); onInterrupt(() => { clearInterval(timer); }); }) ); export const delay_ = (async: Async, ms: number): Async => chain_(sleep(ms), () => async); export const delay = (ms: number) => (async: Async): Async => delay_(async, ms); export const result = (async: Async): Async> => foldM_(async, flow(failure, succeed), flow(success, succeed)); export const onInterrupt_ = ( async: Async, onInterrupted: () => Async ): Async => new FinalizeInstruction(async, onInterrupted); export const onInterrupt = (onInterrupted: () => Async) => ( async: Async ): Async => onInterrupt_(async, onInterrupted);