rjhilgefort
3/24/2018 - 5:27 PM

Promise Utils FP

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)