Search code examples
javascriptajaxeventspollingbacon.js

bacon.js EventStream representing polling of url at interval


I want to poll a url regularly and get the results as a stream. I'm probably missing something obvious but does anyone know how to do this seemingly simple thing in bacon.js?


Solution

  • Figured it out, this will poll /whatever every 5 seconds and return the results as a stream of values:

    var ajaxE = function() {
      return Bacon.fromPromise(
        $.ajax({
          type: "GET",
          url: "/whatever",
          dataType: "JSON"
        })
      );
    };
    
    var stream = Bacon.interval(5000).flatMapLatest(ajaxE);
    

    Explained here: http://nullzzz.blogspot.com/2012/12/baconjs-tutorial-part-iii-ajax-and-stuff.html (section titled "AJAX with flatMap").