Created
May 26, 2023 14:23
-
-
Save edew/cb813b34e422da282a8858df821763c8 to your computer and use it in GitHub Desktop.
Thenable results
This file contains 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
// For bonus points | |
// * ensure then/catch is always asynchronous | |
// * flatten f functions that return thenables | |
class Success { | |
constructor(v) { | |
this.v = v | |
} | |
then(f) { | |
return f(this.v) | |
} | |
catch(f) { | |
return this | |
} | |
} | |
class Failure { | |
constructor(v) { | |
this.v = v | |
} | |
then(f) { | |
return this | |
} | |
catch(f) { | |
return f(this.v) | |
} | |
} | |
/* | |
const a = () => new Success(1) | |
const b = (x) => new Promise((r) => { | |
r(new Success(x + 1)) | |
}) | |
const c = (x) => x + 1 | |
const d = (x) => Promise.resolve(x + 1) | |
const err = () => Promise.reject('error') | |
a() | |
.then(b) | |
.then(c) | |
.then(d) | |
.then(x => { console.log(x) }) | |
a() | |
.then(b) | |
.then(err) | |
.then(c) | |
.then(d) | |
.then(x => { console.log(x) }) | |
.catch(x => { console.error(x) }) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment