Created
May 11, 2020 20:34
-
-
Save benjamingr/1c15fd6408181ca81e7862fea60358b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a non recursively assimilating promise without error recovery | |
class NonAssimilatingPromise<T, E> { | |
public value?: T; | |
constructor(value?: T, public error?: E) { | |
if (value) { | |
this.value = value; | |
} | |
} | |
then<T2, E2>(fn: (value: T) => NonAssimilatingPromise<T2, E2>): NonAssimilatingPromise<T2, E | E2> { | |
if (this.error) { | |
return new NonAssimilatingPromise<T2, E>(undefined, this.error); | |
} | |
if (!this.value) { | |
// this is where real promises wait and queue, a real then doesn't invoke the function it creates a new | |
// promise and "resolves it with a then to this promise". | |
throw new Error("we don't actually do deferred execution ¯\_(ツ)_/¯") | |
} | |
const result = fn(this.value); | |
return result; | |
} | |
static resolve<T>(value?: T) { | |
return new NonAssimilatingPromise<T, never>(value); | |
} | |
static reject<E>(error?: E) { | |
return new NonAssimilatingPromise<never, E>(undefined as never, error); | |
} | |
}; | |
let { error, value } = NonAssimilatingPromise.resolve(3).then((num) => { | |
if (num > 3) { | |
return NonAssimilatingPromise.reject(new TypeError('hello world')); | |
} | |
return NonAssimilatingPromise.resolve('hello'); | |
}).then((str) => { | |
typeof str; // string | |
if (str.length > 4) { | |
return NonAssimilatingPromise.reject(new ReferenceError('Got a reference error')); | |
} | |
if (str.length < 2) { | |
return NonAssimilatingPromise.reject(new RangeError('range')); | |
} | |
return NonAssimilatingPromise.resolve(42); | |
}).then((num) => { | |
if (num > 1000) { | |
return NonAssimilatingPromise.reject(new Error('Shouldn\'t get here!')); | |
} | |
return NonAssimilatingPromise.resolve(num); | |
}); | |
typeof error; // TypeError | Error | ReferenceError | |
typeof value; // number |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment