Search code examples
clojurescript

How do I handle a standard .then style callback in clojurescript?


Suppose I wanted to ask something of the browser, like this JS example:

if (navigator.requestMIDIAccess) {
  console.log('WebMIDI is supported in this browser.');
  navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);

How would I do that in ClojureScript? I see some examples for AJAX style web requests, and some really complicated scenarios, and so on, but what is the simplest route?


Solution

  • if (navigator.requestMIDIAccess) {
      console.log('WebMIDI is supported in this browser.');
      navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);
    }
    

    Simply translates too:

    (when (.-requestMIDIAccess navigator)
      (.log js/console "WebMIDI is supported in this browser.")
      (.then (.requestMIDIAccess navigator) on-midi-success on-midi-failure))
    

    Where on-midi-success and on-midi-failure are some function you defined prior to handle the promise being fulfilled or rejected.

    So basically .then style callbacks are handled exactly the same in ClojureScript as they are in JavaScript.