Skip to content

Instantly share code, notes, and snippets.

@rjhilgefort
Last active January 7, 2019 22:51
Show Gist options
  • Save rjhilgefort/49388e82b4d702376d1865eada563255 to your computer and use it in GitHub Desktop.
Save rjhilgefort/49388e82b4d702376d1865eada563255 to your computer and use it in GitHub Desktop.
Some utils to compose promise more easily.
console.clear()
///////////////////////////////////////////////////////////////
// promise-utils.js
// PromiseAll :: Promise.all
const PromiseAll = (x) => Promise.all(x)
// thenP :: Function -> Promise -> Promise
const thenP =
R.curry((success, promise) => promise.then(success))
// thenP2 :: Function -> Function -> Promise -> Promise
const thenP2 =
R.curry((success, error, promise) => promise.then(success, error))
// catchP :: Function -> Promise -> Promise
const catchP =
R.curry((error, promise) => promise.catch(error))
// mapP :: Function -> Object|Array a -> Promise<a>
const mapP = R.curry(
(xf, data) => R.compose((x) => Promise.all(x), R.map(xf))(data)
)
const throwT =
R.curry((label, x) => { throw new Error(`${label}: ${x}`) })
// ... TODO: More
///////////////////////////////////////////////////////////////
// app.js
const fromServer =
x => Promise.resolve(`fetched: ${x}`)
const isDucks = R.equals('fetched: ducks')
const app = compose(
catchP(always('Fine, ducks are okay this time')),
thenP(R.toUpper),
thenP(R.when(isDucks, throwT('Ducks not allowed'))),
fromServer,
)
///////////////////////////////////////////////////////////////
// index.js
app('birds').then(console.log)
app('ducks').then(console.log)
@rjhilgefort
Copy link
Author

all, race, finally

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