Skip to content

Instantly share code, notes, and snippets.

@edew
Created May 26, 2023 14:23
Show Gist options
  • Save edew/cb813b34e422da282a8858df821763c8 to your computer and use it in GitHub Desktop.
Save edew/cb813b34e422da282a8858df821763c8 to your computer and use it in GitHub Desktop.
Thenable results
// 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