Skip to content

Instantly share code, notes, and snippets.

@r17x
Created January 7, 2024 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r17x/f58183d2891d5f21272bc50dab55b076 to your computer and use it in GitHub Desktop.
Save r17x/f58183d2891d5f21272bc50dab55b076 to your computer and use it in GitHub Desktop.
Promise101

Promise is Like a MONAD but Never be a MONAD

// same thing: f(x)
const apply = (x, f) => f(x)

const touch = (f) => (x) => {
  apply(x, f)
  return x
}

// same thing: (f,g) => x => f(g(x))
const pipe =
  (...xs) =>
  (v) =>
    xs.reduce(apply, v)

// same thing: Promise.resolve(1).then(f)
const map = (f) => (p) => p.then(f)

const tap = (f) => (p) => p.then(touch(f))

// same thing: Promise.reject(1).catch(f)
const mapE = (f) => (p) => p.catch(f)

const tapE = (f) => (p) => p.catch(touch(f))

// same thing: Promise.resolve(1).then(f).catch(() => d)
const mapWithDefault = (f, d) =>
  pipe(
    map(f),
    mapE(() => d)
  )

const github = {
  user: (username) => `https://api.github.com/users/${username}`,
}

const responseJson = (r) => r.json()

// same thing
// 	const fetchUserByUsername = username => fetch(endpoints.user(username))
const fetchUserByUsername = pipe(
  github.user,
  fetch,
  mapWithDefault(responseJson, null)
)

const getUser = pipe(
  fetchUserByUsername,
  tap(result => console.info(`What's [result]: `, {result})),
)

// getUser('username')
// Promise { ❓ }

You could be try and run this code with devTools (simply copy-paste) and call getUser(CHANGEME)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment