How to create an async function in Clojurescript? - clojurescript

Is there a way in Clojurescript create an async function or a macro wrap a function into a Promise to simulate it?
My current use-case is to replace the following function that takes a callback by its async version - btw this is for an AWS lambda function.
// Old style
function(args, callback) {
// Use callback(e) for errors
// Use callback(null, value) for the result
}
// New style
async function(args) {
return value; // success path
throw new Error(); // error path
}
Given that this is Clojurescript, using await is not the question. And I know this can simply return a Promise to comply with the async requirement.
So it resolves to some sugar code to create the Promise, catch all errors for me and calling resolve on the happy path or reject otherwise.
Browsing through clojure.core.async and docs -including the clojurescript reference, I haven't found anything.

Node 8 and newer ship with util.promisify that does what you want:
Takes a function following the common error-first callback style, i.e. taking a (err, value) => ... callback as the last argument, and returns a version that returns promises.
EDIT: I spent a bit writing a macro that does promisify and I'm safisfied with the result. Note that the macro needs to be saved in a CLJC file:
;; macros.cljc ;;;;;;;;;;
(ns server.macros)
(defmacro promisify [method obj params]
`(js/Promise.
(fn [resolve# reject#]
(~method ~obj ~params
(fn [err# result#]
(if err#
(reject# err#)
(resolve# result#)))))))
;; main.cljs ;;;;;;;;;;
(ns server.main
(:require-macros [server.macros :refer [promisify]])
(:require ["aws-sdk" :as aws]))
(defn main! []
(println "App loaded...")
(let [creds (aws/SharedIniFileCredentials. #js {:profile "example-profile"})
_ (set! (.-credentials aws/config) creds)
s3 (aws/S3.)]
(-> (promisify .listBuckets s3 #js {})
(.then #(println "DATA:" %))
(.catch #(println "ERROR:" %)))))
and the output is the same as before:
$ node target/main.js
App loaded...
DATA: #js {:Buckets #js [#js {:Name demo-test-bucket, :CreationDate #inst "2019-05-05T17:32:17.000-00:00"} #js {:Name subdomain.mydomain.com, :CreationDate #inst "2019-06-19T04:16:10.000-00:00"}], :Owner #js {:DisplayName username, :ID 9f7947b2d509e2338357d93e74f2f88a7528319ab3609b8d3b5be6b3a872dd2c}}
The macro is basically a Clojure version of this code.
EDIT 2: There's also this library that could be interesting if you really want to use core.async too.

Related

How to return a promise from a go block?

The question is how to send to a nodejs app the result of a go block
i found a solution with callback
but i need a solution with promise
Promise solution?
Clojurescript app
(defn foo []
(go 1))
;;how to change foo,wrap to promise?, so node app can await to get the 1
;;i used 1 for simplicity in my code i have something like
;;(go (let [x (<! ...)] x))
Node app
async function nodefoo() {
var x = await foo();
console.log(x); // i want to see 1
}
Callback solution (the one that works now)
So far i only found a way to pass a cb function, so this 1 goes back to node.js app
Clojurescript app
(defn foo1 [cb]
(take! (go 1)
(fn [r] (cb r))))
Node app
var cb=function () {....};
foo1(cb); //this way node defined cb function will be called with argument 1
But i dont want to pass a callback function, i want node.js to wait and get the value.
I want to return a promise.
This function takes a channel and returns a Javascript Promise that resolves with the first value the channel emits:
(defn wrap-as-promise
[chanl]
(new js/Promise (fn [resolve _]
(go (resolve (<! chanl))))))
Then to show usage:
(def chanl (chan 1))
(def p (wrap-as-promise chanl))
(go
(>! chanl "hello")
(.then p (fn [val] (println val))))
If you compile that and run it in your browser (assuming you called enable-console-print!) you'll see "hello".
It is also possible to extend the ManyToManyChannel type with extend-type.
Here's a naif implementation using a similar wrap-as-promise function
(require '[clojure.core.async.impl.channels :refer [ManyToManyChannel]])
(defn is-error? [val] (instance? js/Error val))
(defn wrap-as-promise
[channel callback]
(new js/Promise
(fn [resolve reject]
(go
(let [v (<! channel)]
(if (is-error? v)
(reject v)
(resolve (callback v))))))))
(extend-type ManyToManyChannel
Object
(then
[this f]
(wrap-as-promise this f)))
(def test-chan (chan 1))
(put! test-chan (new js/Error "ihihi"))
(put! test-chan :A)
(defn put-and-close! [port val]
(put! port val)
(async/close! port))
(-> test-chan
(.then (fn [value] (js/console.log "value:" value)))
(.catch (fn [e] (js/console.log "error" e)))
(.finally #(js/console.log "finally clause.")))

How to implement *load-fn* for :requires in bootstrapped clojurescript

(ns scratch
(:require [cljs.js :as cjs]))
;Let's setup a simple clojurescript string eval that supports namespaces:
(def current-ns 'cljs.user)
(def compiler-state (cjs/empty-state))
(defn eval-text [text]
(println string)
(cjs/eval-str compiler-state text current-ns
{:eval cjs/js-eval
:ns current-ns
:context :expr
:def-emits-var true}
(fn [result]
(set! current-ns (:ns result))
(println result))))
(eval-text "(ns a.a)")
(eval-text "(defn add [a b] (+ a b))")
(eval-text "(add 4 4)")
;I can refer to the function from another namespace explicitly with no problem
(eval-text "(ns x.x)")
(eval-text "(a.a/add 6 6)")
;However when I do
(eval-text "(ns b.b (:require [a.a :refer [add]]))")
On the last line I get:
{:error #error {:message Could not require a.a, :data {:tag :cljs/analysis-error}, :cause #object[Error Error: No *load-fn* set]}}
So I have to create my own https://cljs.github.io/api/cljs.js/#STARload-fnSTAR
and pass it into the :load compiler option to handle this :require even though the compiler state already knows about my namespace as I can call the fully qualified function from another namespace.. Correct?
What is the best way to do that?
Should I create maps that store namespace->source-code from previously evaled code and get namespace->analysis-cache from the compiler state and pass these into the :source and :cache callbacks of my custom load function?
Is there a better / more efficient way to do this?
I believe I found the answer:
The :load option of eval-str can be set to the following function:
(defn load-dep [opts cb]
(cb {:lang :js :source ""})
And it will quite happily resolve. This isn't really apparent from the documentation that the callback can return this value when the namespace/var is already in the compiler state so I'll leave the question here.

How do I extract the body from an HTTP request in Clojure?

I am making an HTTP request:
(defn main-panel []
(def API-URL "https://api.chucknorris.io/jokes/random")
(defn getFileTree []
(go (let [response (<! (http/get API-URL
{:with-credentials? false
:headers {"Content-Type" "application/json"}}))]
(:status response)
(js/console.log (:body response))))) ; prints a very complex data structure
(go
(let [result (<! (getFileTree))]
(.log js/console (:body result)))) ; prints null
:reagent-render
(fn []
[:h1 "kjdfkjndfkjn"]))
But I can't get to the "joke" in the returned object, array item 13:
How do I assign this value to a let or def?
Also, why does the second console.log print null?
Update
I am now moving on from using reagent atoms to reframe.
This is my component that successfully GETs data, updates the re-frame 'database':
(defn main-panel []
(def API-URL "https://api.chucknorris.io/jokes/random")
(def request-opts {:with-credentials? false})
(defn getFileTree []
(go (let [response (<! (http/get API-URL request-opts))]
(re-frame/dispatch [:update-quote response]))))
(defn render-quote []
(println (re-frame/subscribe [::subs/quote])) ;successfully prints API data as in screenshot below
(fn []
(let [quote-data (re-frame/subscribe [::subs/quote])
quote-text (if quote-data (:value quote-data) "...loading...")]
[:div
[:h3 "Chuck quote of the day"]
[:em quote-text]])))
(fn []
(getFileTree)
[render-quote]))
But this is the object I get back from the re-frame database:
As you can see it comes wrapped in the Reaction tags and I can't access the body or value any more. How do I access those?
I have a small working version using the reagent template. Create a new project (assuming you have Leiningen installed) with: lein new reagent chuck. This will create a project with many dependencies, but it works out of the box.
Next, edit the file at src/cljs/chuck/core.cljs and edit it so it looks like the following:
(ns chuck.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [reagent.core :as reagent :refer [atom]]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]))
(def api-url "https://api.chucknorris.io/jokes/random")
(def request-opts {:with-credentials? false
:headers {"Content-Type" "application/json"}})
(def api-response (atom nil))
(defn get-quote []
(go
(let [response (<! (http/get api-url request-opts))]
(println response)
(reset! api-response response))))
(defn render-quote []
(fn []
(let [quote-data (:body #api-response)
quote-text (if quote-data (:value quote-data) "...loading...")]
[:div
[:h3 "Chuck quote of the day"]
[:em quote-text]])))
(defn quote-page []
(fn []
(do
(get-quote)
[:div
[:header
[render-quote]]
[:footer
[:p "footer here"]]])))
;; -------------------------
;; Initialize app
(defn mount-root []
(reagent/render [quote-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
I'll explain the relevant bits:
init will bootstrap the basics of the front-end, but in our case it's just calls mount-root which starts reagent telling it to call quote-page and placing the results in the DOM replacing the element with the ID of app.
quote-page calls get-quote which will call the API using the cljs-http library. I'm not checking for errors here, but basically when the request completes (either success or error) it will read the results from the channel (using <!) and place the response in response. The key is that response is a nested ClojureScript map that you can inspect to check if the result was successful or not. Note that I'm also printing the results with println instead of JS interop (.log js/console xxx) because console.log will show the inner details of how the nested map is implemented, which is not relevant for this case.
One the response is available, I store the results of the response in an atom called api-response. The key here is that the atom will contain nothing for a bit (while the request completes) and then the response will be inside it and reagent will take care of detecting the change and re-rendering.
Finally, quote-page calls render-quote which generates the markup for rendering the quote or a placeholder while it loads.
To run the whole thing, open a terminal and run lein run which will start a web server listening on port 3000 by default. In another terminal, run lein figwheel which will compile the ClojureScript code for you. One figwheel is ready it will start a REPL, and you can open the address http://0.0.0.0:3000/ in your computer to view the page.

how to do ajax request in clojurescript with reagent?

Say I have a component which needs to request some data from server before rendering.
What I have now is something like with cljs-ajax library:
(def data (r/atom nil))
(defn component [id]
(r/create-class {:reagent-render simple-div
:component-did-mount (partial get-data id)}))
(defn get-data [id]
(GET (str "/api/" id)
{:handler init}))
(defn init [response]
(let [data1 (:body response)
data2 (compute data1)
data3 (compute2 data2)]
(reset! data (compute3 data1))
(.setup #data data1)
(.setup2 #data data2)
(.setup3 #data data3))
the setup functions are some foreign JS library functions with side effects.
This works but I don't feel like this is the correct way to do callback.
Not to mention if I need to GET other datas based on the first data I got, and then other datas based on that, it would be a very nasty chain of callbacks.
Is there a better, clean way of doing this kind of ajax request in reagent/clojurescript?
The most common way to make requests is cljs-http. Add [cljs-http "0.1.39"] to the dependencies in project.clj and restart the figwheel process in the terminal to pick up the new dependency.
(ns my.app
(:require
[cljs.core.async :refer [<!]] [cljs-http.client :as http])
(:require-macros [cljs.core.async.macros :refer [go]])
(go (let [response (<! (http/get "data.edn"))]
(prn (:status response))
(prn (:body response))))
Cljs-http is a nice way to manage HTTP requests. It uses core.async channels to deliver its results. For now, all you need to focus on is that http/get and http/post calls should occur inside a go form, and the result is a channel that can have its result read with
Dependent http gets can be chained together in a sensible way in a single go block that looks like sequential code, but occurs asynchronously.

How to call om.dom/render-to-str in Emacs nrepl?

I would like to display the html output of the following object:
(defn search-input [_ owner]
(reify
om/IInitState
(init-state [_]
{:text nil})
om/IRenderState
(render-state [this state]
(dom/input
#js {:type "text"
:value (:text state)
:className "form-control"
:onChange (fn [event] (handle-change event owner state))}))))
There is a render-to-str method in om.dom. But if I type
om.dom/render-to-str
in the ClojureScript repl all I get is nil. And calling om.dom/render-to-str gives the correspondign error message.
TypeError: 'undefined' is not an object (evaluating 'om.dom.render_to_str.call')
The strange thing: Code completion in the repl gives me the render-to-str call.
Ok the problem with om.dom/render-to-str returning nil is solved. The problem was that I didn't connect to a real browser repl but a headless repl. Therefore no index.html was loaded and therefore not react.js was loaded.
But now calling
(dom/render-to-str (search-input nil {}))
returns
"Error evaluating:" (dom/render-to-str (search-input nil {})) :as "om.dom.render_to_str.call(null,om_oanda.core.search_input.call(null,null,cljs.core.PersistentArrayMap.EMPTY));\n"
#<Error: Invariant Violation: renderComponentToString(): You must pass a valid ReactComponent.>
Error: Invariant Violation: renderComponentToString(): You must pass a valid ReactComponent.
After some more tests I think I have to change the call like this:
(dom/render-to-str (om.core/build search-input a-cursor {}))
So the last question is: How do I create a cursor.
(defn render-to-str
"Equivalent to React.renderComponentToString"
[c]
(js/React.renderComponentToString c))
Try calling the function with the component as an argument.