Skip to content

Instantly share code, notes, and snippets.

@audionerd
Last active May 27, 2018 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audionerd/43945377eb4b53a22271b2d62ae08593 to your computer and use it in GitHub Desktop.
Save audionerd/43945377eb4b53a22271b2d62ae08593 to your computer and use it in GitHub Desktop.
Callbags and Canceling with CAF
require('regenerator-runtime/runtime')
import { forEach, map, pipe, fromEvent, scan } from 'callbag-basics'
import CAF from 'caf'
let source = pipe(
fromEvent(document, 'keydown'),
map(event => function * (signal) {
console.log('%cbegin', 'color:red')
yield CAF.delay(signal, 1000)
console.log('%cend', 'color:green')
return 'complete!'
}),
scan((coll, fn) => {
if (coll.token) coll.token.abort('cancel')
coll.token = new CAF.cancelToken()
return { token: coll.token, fn }
}, {}),
map(({ token, fn }) =>
CAF(fn)(token.signal)
)
)
forEach(p =>p
.then(result => console.log(result))
.catch(canceled => console.log(canceled))
)(source)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment