How do you abort a Bacon.js Property that is making an AJAX request once 404 is reached?

StackOverflow https://stackoverflow.com/questions/18750329

  •  28-06-2022
  •  | 
  •  

Frage

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?

War es hilfreich?

Lösung

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 })

Andere Tipps

You could simply say .endOnError() instead of .mapError("") to end on any error.

If you need more specific handling per error type, you can do

loadImg404 = loadImg.mapError(".status").filter(function(status) { return status==404 })
...
loadImg.takeUntil(loadImg404).onValue(..)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top