Last active
January 7, 2019 22:51
-
-
Save rjhilgefort/49388e82b4d702376d1865eada563255 to your computer and use it in GitHub Desktop.
Some utils to compose promise more easily.
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
all, race, finally