Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save refractalize/4773544 to your computer and use it in GitHub Desktop.
Save refractalize/4773544 to your computer and use it in GitHub Desktop.

Having a wee bit o trouble with the async paradigm?

pogoscript has a calling convention for async functions, taken from the Node.js fs module, many other libraries use it, but not all. The callback is called like this:

callback(error, result);

So

fs.readFile(filename, function (error, result) { ... });

The problem below is that the twitter API doesn't follow this convention (rightly or wrongly) but the effect is that pogoscript thinks that the tweet is the error, not the result. What you'd need to do is wrap twit.get to follow the convention:

get tweet! (url) =
    twit.get (url) @(tweet)
        continuation (nil, tweet)

Then you can call it using pogoscript's async notation:

tweet = get tweet! '/statuses/show/301416893036761088.json'
response.writeHead (200, 'Content-Type': 'text/plain')
response.end (tweet.text)

There's pretty scant documentation about this so I've been meaning write more examples.

Actually you can make your code a bit more robust with a try catch...

Instead of:

app.get '/tweet' @(req, res)
    result = ...
    res.end (result)

Which may result in no response being sent if there is an error, you can try this:

app.get '/tweet' @(req, res)
    try
        tweet = get tweet! '/statuses/show/301416893036761088.json'
        res.write head (200, "Content-Type", "text/plain")
        res.end (tweet)
    catch (ex)
        res.write head (500, "Content-Type", "text/plain")
        res.end (ex)

The idea with this is that you correctly write a response regardless of whether your action succeeds or fails. All exceptions are handled for you.

Once you've wrapped some of the more esoteric async interfaces in Node land your code ends up being much easier to read and write.

var twit = new twitter();
twit.get ('/statuses/show/301416893036761088.json', function(tweet){
response.writeHead(200, {"Content-Type": "text/plain"});
response.end(tweet.text);
})
twit = @new twitter()
tweet = twit.get! ('/statuses/show/301416893036761088.json')
response.writeHead (200, 'Content-Type': 'text/plain')
response.end (tweet.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment