How can I approach the javascript / clojurescript wrapper library for api?

I am primarily a Python developer, but lately I am trying to learn Clojure / ClojureScript. As a practice, I want to write a ClojureScript wrapper for the Reddit API.

Most of my confusion is related to the asynchronous nature of Javascript. Since AJAX functions do not actually return an API response, how can I write a shell so that it works somewhat similar to synchronous server-side requests?

Or is this not possible at all, and should I use callbacks for every API call in my application (and therefore the wrapper library will be pointless)?

Are there any similar libraries where I can link? (Javascript / ClojureScript)

+4
source share
2 answers

You can make synchronous XHR requests, but this is not idiomatic. Javascript (and Clojurescript by extension) uses a single-threaded execution model, so long calls are usually asynchronous to avoid blocking the execution of other parts of the application. If you are writing a wrapper for a synchronous API, you usually add a callback parameter for each API method (and remember to provide some form of error handling).

As for your specific question, accessing the reddit API from a browser almost certainly violates the same origin policy : you can usually make AJAX requests to the domain that served the original Javascript. Usually, when you want to provide access to a third-party service on the client side (browser-based), you do this by proxying client requests through your server. The server must ensure that it requests only authorized clients. If you decide to use this route, you will make an asynchronous request from your browser using clojurescript to your web server (presumably by running clojure), which will authenticate the request and then make a synchronous request in the reddit API and return the result for the client. When the answer is ready, the client will call a callback and your code will get the result.

+1
source

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

There are several libraries in Python that implement futures. The most famous are Twisted and Tornado , however Tulip is a new library that will most likely be used as the default implementation of the event loop for Python 3.4 .

The same story is true in JavaScript. Many popular ( jQuery included ) implement futures, letting you do this:

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

in it:

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

All Articles