Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jethrolarson
Last active August 29, 2015 14:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jethrolarson/6d17028985f502592faf to your computer and use it in GitHub Desktop.
Save jethrolarson/6d17028985f502592faf to your computer and use it in GitHub Desktop.
Playing with Future
var R = require('ramda');
var Future = require('ramda-fantasy').Future;
//Wrap ajax in a future
//:: String -> Future String
var fetch = function(url) {
return new Future(function(rej, res){
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", res, false);
oReq.addEventListener("error", rej, false);
oReq.addEventListener("abort", rej, false);
oReq.open("get", url, true);
oReq.send();
});
};
//:: String -> Future Object
// Could use Either instead of Future but they work about the same.
var parseJSON = function(str){
return new Future(function(rej, res){
try {
res(JSON.parse(str));
} catch (err) {
rej({error: "json parse error"});
}
});
};
//We have
// String -> Future String
// And
// String -> Future Object
// So we can .chain() them together
var fetchJSON = fetch.chain(parseJSON);
// Get the items out of it?
//:: Future Object -> Future []
var fetchItems = fetchJSON.map(R.prop('items'));
//BTW at this point in the code the request still hasn't been sent
// Filter the response?
// Have to map first to get at the contents of the future then filter
//:: Future [Object] -> Future [Object]
var fetchNewItems = fetchItems.map(R.filter(R.prop('new')))
// Just get the titles of the items
//:: Future [Object] -> Future [String]
var getNewTitles = fetchNewItems.map(R.map('title'));
//Finally do something
getNewTitles.fork(console.log, console.log);
//Now the AJAX req is sent and will log success or failure to console.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment