Skip to content

Instantly share code, notes, and snippets.

@steve-taylor
Created March 6, 2022 23:48
Show Gist options
  • Save steve-taylor/6b187f2a518360914c4bd013f107d5bb to your computer and use it in GitHub Desktop.
Save steve-taylor/6b187f2a518360914c4bd013f107d5bb to your computer and use it in GitHub Desktop.
Bacon.js fetch wrapper with AbortController support
import {fromBinder} from 'baconjs'
/**
* Create a Bacon.js EventStream that fetches a resource specified by the fetch
* parameters.
*
* If the EventStream loses all subscriptions while the underlying request is pending,
* the request will be aborted using <code>AbortController</code>. NOTE: If
* <code>init.signal</code> is provided, it will be ignored in favour of an internally
* provided signal.
*/
function fetchBacon(input, init): EventStream {
return fromBinder(sink => {
const controller = new AbortController()
fetch(url, {...init, signal: controller.signal})
.then(res => sink(res.ok ? res : new Bacon.Error(res)))
.catch(error => sink(new Bacon.Error(error)))
.finally(() => sink(new Bacon.End()))
return () => controller.abort()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment