Any syntax to match async/await in creating web servers?

Promise is part of the spec for async/await so every engine is doing it that way.

Sure you can use koa with ClojureScript. There is no magic involved.

(ns demo.server
  (:require ["koa" :as koa]
            [clojure.string :as str]))

(defonce app-ref (atom nil))

(defn handler [ctx next]
  (set! (. ctx -body) "hello world")
  (next))

(defn delay-by-two-seconds [ctx next]
  (-> (js/Promise.
        (fn [resolve reject]
          (js/setTimeout resolve 2000)))
      (.then next)))

(defn upcase-async [ctx next]
  (-> (next)
      (.then
        (fn []
          (set! (. ctx -body) (str/upper-case (. ctx -body)))
          ))))

(defn main []
  (let [app (koa.)]
    (reset! app-ref app)

    (doto app
      (.use delay-by-two-seconds)
      (.use handler)
      (.use upcase-async)
      (.listen 3000))))

At least thats what I can gather from glancing over the docs. It is all built on top of the usual “middleware” stack. So each “use” is supposed to call “next” while making any adjustments to “ctx” it wants (mutable object). It is build on top of Promise.resolve so a handler may either return a Promise or any other value.

You can hook this up with core.async by using a little utility that created a Promise that resolves once a go block finishes.

I might be wrong, I literally looked at the docs for 30 seconds. It is just based on Promise nothing else. async/await is just syntax sugar for that and not required at all.

2 Likes