Skip to content

Instantly share code, notes, and snippets.

@r17x
Created October 30, 2023 12:33
Show Gist options
  • Save r17x/fecb9f6843c18ef068ca82cc2ac31cd2 to your computer and use it in GitHub Desktop.
Save r17x/fecb9f6843c18ef068ca82cc2ac31cd2 to your computer and use it in GitHub Desktop.
Promise!01!
const _data = (data) => ({ error: null, data })
const _error = (error) => ({ data: null, error })
const mapError = f => ({ error, data }) => ({ error: f(error), data })
const mapData = f => ({ error, data }) => ({ data: f(data), error })
const promiseMapData = f => p => p.then(f)
const promiseMapError = f => p => p.catch(f)
const promiseMe = (p) => pipe(
p,
promiseMapData(_data),
promiseMapError(_error)
)
const input = promiseMe(Promise.resolve(1))
// Promise {data: 1, error: null}
const jsonFromRest = pipe(
fetch('/x'),
promiseMapData(r => r.json()),
promiseMe,
)
// ✅: Promise { data: {ping: 1}, error: null }
// ❌: Promise { data: null, error: "FAFIFUFE" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment