Skip to content

Instantly share code, notes, and snippets.

@branneman branneman/solution1.js
Last active Aug 5, 2019

Embed
What would you like to do?
Declarative asynchonous control flow: promises, observables, futures
const wrapPromise = fn => (...args) =>
new Promise(resolve => setTimeout(
() => resolve(fn(...args)),
Math.floor(Math.random() * 1500) + 250)
)
const upper = wrapPromise(str => str.toUpperCase())
const underline = str => `__${str}__`
const exclamate = wrapPromise(str => str + '!')
// Util: Create promise chain
const chainPromises = (...fns) => val =>
fns.reduce((ch, fn) => ch.then(fn), Promise.resolve(val))
// Create function chain with mixed sync and async functions
const chain1 = chainPromises(upper, underline, exclamate, console.log)
;['aap', 'noot', 'mies'].forEach(chain1)
const Observable = require('zen-observable')
const wrapPromise = fn => (...args) =>
new Promise(resolve => setTimeout(
() => resolve(fn(...args)),
Math.floor(Math.random() * 1500) + 250)
)
const upper = wrapPromise(str => str.toUpperCase())
const underline = str => `__${str}__`
const exclamate = wrapPromise(str => str + '!')
// Util: Promise to Observable
const wrapObservable = fn => (...args) =>
new Observable(observer => {
fn(...args).then(val => observer.next(val))
})
// Create function chain with mixed sync and async functions
const chain2 = Observable.from(['wim', 'zus', 'jet'])
.flatMap(wrapObservable(upper))
.map(underline)
.flatMap(wrapObservable(exclamate))
chain2.subscribe(console.log)
const { map, chain, pipe } = require('ramda')
const { Future, fork } = require('fluture')
const wrapFuture = fn => (...args) =>
Future((_reject, resolve) => {
setTimeout(
() => resolve(fn(...args)),
Math.floor(Math.random() * 1500) + 250
)
})
const upper = wrapFuture(str => str.toUpperCase())
const underline = str => `__${str}__`
const exclamate = wrapFuture(str => str + '!')
// Create function chain with mixed sync and async functions
const chain3 = pipe(
Future.resolve,
chain(upper),
map(underline),
chain(exclamate),
fork(console.error)(console.log)
)
map(chain3)(['teun', 'vuur', 'gijs'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.