4
votes

I'm primarily a Python developer, but I've been trying to learn Clojure/ClojureScript lately. As practice, I want to write a ClojureScript wrapper for Reddit's API.

Most of my confusion is due to the asynchronous nature of Javascript. Since AJAX functions don't actually return the response from the API, how do I write the wrapper so it works somewhat similarly to synchronous server-side requests?

Or is this not possible at all, and I have to use callbacks for each call to the API in my app (and thus a wrapper library would be pointless)?

Are there similar libraries out there I can reference? (Javascript/ClojureScript)

2
You can opt to make you AJAX call synchronously, would that do it?boisvert

2 Answers

1
votes

It is possible to make synchronous XHR requests, but it's not idiomatic. Javascript (and Clojurescript by extension) uses a single-threaded execution model, so long-running calls are typically asynchronous to avoid blocking execution of other parts of the application. If you were writing a wrapper for a synchronous API you would typically add a callback parameter to each API method (and don't forget to provide some form of error handling).

Regarding your specific question, accessing the reddit API from a browser almost certainly violate same origin policy: you can typically only make AJAX requests to the domain that served the original Javascript. Usually when you want to provide client-side (browser-based) access to a third-party service you do this by proxying the client requests through your server. The server should ensure that it only proxies requests from authorised clients. If you decided to take this route, you'd make an asynchronous request from your browser using clojurescript to your webserver (presumably running clojure), which would authenticate the request, then make a synchronous request to the reddit API and return the result to the client. When the response is ready the client will invoke the callback and your code will receive the result.

0
votes

The concept you are looking for is known to most programming languages as "futures". JavaScript libraries that implement such things generally refer to futures as "promises".

In Python there are several libraries that implement futures. The most well known are Twisted and Tornado, however, Tulip is an up-and-coming library that will most likely land as the default event loop implementation for Python 3.4.

The same story is true in JavaScript. Many popular libraries (jQuery included) provide an implementation of futures, letting you turn this:

function makeTwoAsyncCalls(errorCallback, successCallback) {
    ajaxRequest(errorCallback, function onSuccess(data) {
       processWithWebWorker(errorCallback, successCallback);
    });
}

into this:

function doWorkAsync(errorCallback, successCallback) {
    return ajaxRequest()
        .then(processWithWebWorker)
        .then(successCallback)
        .fail(errorCallback);
}