I have some Property
that is making AJAX requests on fire. However, once case 404
is reached, I'd like to terminate this stream, but I'm not sure how to do so. Below is the code:
// load :: EventStream (Int -> Int)
load = $("#loadimg")
.asEventStream("click")
.map(function(e){ return function(x){ return x + 1 }})
// loadP :: Property Int
loadP = load.scan(1, function(x,f){ return f(x) })
// loadImg :: Property (HttpRequest -> Either String String)
loadImg = loadP
.flatMapLatest(function(i){ return Bacon.fromPromise(imgLoader(i) )})
.mapError("")
// imgLoader :: Int -> HttpRequest String
imgLoader = function(id){
// pretend src, root and fmt are global variables
var url = src + root + id + fmt
return $.ajax({
type : "GET",
url : url,
})
.then(function(ys){ return url })
}
// EventStreamT (State Dom) String
loadImg.onValue(function(url){
if (url.length == 0) return url
else return appendImg("#imgs", "name", url);
})
It doesn't make sense to me to put this "abort bacon property" code in the very last function, where the side-effect is located, but where else would I test for 404
case? And how would I terminate the thread?
In Bacon.js 0.6.17, you can pass a predicate function to endOnError
, so you can do
loadImg = loadP .flatMapLatest(function(i){ return Bacon.fromPromise(imgLoader(i) )}) .endOnError(function(error) { return error.status == 404 })