Skip to content

Instantly share code, notes, and snippets.

@rolangom
Last active September 15, 2018 02:13
Show Gist options
  • Save rolangom/0036b410a386d2db77a2391ea72463af to your computer and use it in GitHub Desktop.
Save rolangom/0036b410a386d2db77a2391ea72463af to your computer and use it in GitHub Desktop.
Compose with Promises, using pointfree programming #javascript #functional #programming #pointfree
let composeP = (...fns) => p =>
fns
.reduceRight(
(acc, it) =>
Array.isArray(it)
? acc.then(it[0], it[1]) // ).catch(
: acc.then(it),
p
);
const throwErr = () => { throw Error('RGT Ahhh Err'); }
// utils
const log =
tag => val =>
(console.log(tag, val), val);
const inc =
a => b => a + b;
const constant = x => () => x;
let reject = msg => Promise.reject(Error(msg))
// implementation
const process = composeP(
constant(99),
[log('succ'), log('eh, sorry')],
// reject,
throwErr,
constant('err klk'),
log('step 2'),
inc(2),
log('step 1'),
inc(1)
);
process(Promise.resolve(1))
.then(log('final')).catch(() => console.log('Por si aca'))
.then(() => console.log('Ahora si'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment