import { LazyValue } from './LazyValue'; export interface Future { readonly map: (mapper: (v: T) => U) => Future; readonly bind: (binder: (v: T) => Future) => Future; readonly anonBind: (thunk: Future) => Future; readonly toLazy: () => LazyValue; readonly toCached: () => Future; readonly toPromise: () => Promise; readonly get: (callback: (v: T) => void) => void; } const errorReporter = (err: any) => { // we can not throw the error in the reporter as it will just be black-holed // by the Promise so we use a setTimeout to escape the Promise. setTimeout(() => { throw err; }, 0); }; const make = (run: () => Promise): Future => { const get = (callback: (value: T) => void) => { run().then(callback, errorReporter); }; /** map :: this Future a -> (a -> b) -> Future b */ const map = (fab: (v: T) => U) => { return make(() => run().then(fab)); }; /** bind :: this Future a -> (a -> Future b) -> Future b */ const bind = (aFutureB: (v: T) => Future) => { return make(() => run().then((v) => aFutureB(v).toPromise())); }; /** anonBind :: this Future a -> Future b -> Future b * Returns a future, which evaluates the first future, ignores the result, then evaluates the second. */ const anonBind = (futureB: Future) => { return make(() => run().then(() => futureB.toPromise())); }; const toLazy = () => { return LazyValue.nu(get); }; const toCached = () => { let cache: Promise | null = null; return make(() => { if (cache === null) { cache = run(); } return cache; }); }; const toPromise = run; return { map, bind, anonBind, toLazy, toCached, toPromise, get }; }; const nu: { (baseFn: (completer: (value: T) => void) => void): Future; (baseFn: (completer: () => void) => void): Future; } = (baseFn: (completer: (value?: T) => void) => void): Future => { return make(() => new Promise(baseFn)); }; /** a -> Future a */ const pure = (a: T): Future => { return make(() => Promise.resolve(a)); }; export const Future = { nu, pure };