Created
March 6, 2022 23:48
-
-
Save steve-taylor/6b187f2a518360914c4bd013f107d5bb to your computer and use it in GitHub Desktop.
Bacon.js fetch wrapper with AbortController support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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