Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I came to Javascript from Ruby/Scheme/Haskell, so when I had to call the Yahoo Search API with a callback, sometimes with two or more searches concurrently, I thought, oh, I'll store the continuation, because they only allow /[A-Za-z0-9.]+/ as characters in the callback.

var fns = [];

function gensym() { return $R(0,20).toArray().map(function(){return String.fromCharCode(Math.random()*26+65)}).join('') }

function storefunc(f) { var g = gensym(); fns[g] = f; return 'fns.'+g }

function jsonk(url,hash,k) { var s = document.createElement('script');

  s.src = url+'?'+$H(hash).merge({'callback': storefunc(k)}).toQueryString();

  document.body.appendChild(s);

  return s.src
}

I learned gensym and web-read-k in Scheme at Brown (thanks, Shriram!), and jsonk turned out to be pretty useful, because the same comtinuation-passing style that's available when you do XHRs now becomes available when you do json requests from a different domain, if they have a callback parameter. (I brought this code to Songkick, and we shortened callback to k.)



http://news.ycombinator.com/item?id=79205

Pretty much entirely continuations. Uses MochiKit.


What's $R and $H doing? I know Javascript, but I don't know all the cool frameworks very well.

Otherwise, this is mad cool.


it's a little kludgy, but here's how it goes:

fns stores continuations. gensym: make an array of 20 random characters (make an array of 20 #s, map each to a random character). storefunc: continuation -> string, and store the continuation in fns, such that eval(string)==continuation jsonk: make a query string from the url, the parameters supplied, and the continuation (change 'callback' to whatever the api calls it), and then add that script to the page, returning the url for debugging purposes.

you could also have a timeout after 30 seconds to say "something went wrong", and that might not be much more code, just set a timeout, and wrap k in jsonk to a function that first stops the delayed error message and then calls k, but that's an exercise for the reader.

but yeah, so

jsonk("http://api.search.yahoo.com/WebSearchService/V1/webSearch",{output:'json',appid:'YahooDemo',query:'britney'},function(r){alert(r.ResultSet.totalResultsAvailable)})

will pop up an alertbox that shows how many hits 'britney' gets on yahoo.



To this day, I wish I'd taken Shriram's class when I had the chance.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: