如何在 clojurescript 中处理标准的 .then 样式回调?

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

假设我想向浏览器询问一些事情,比如这个 JS 示例:

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

我如何在 ClojureScript 中做到这一点?我看到了一些 AJAX 样式 Web 请求的示例,以及一些非常复杂的场景等等,但是最简单的路由是什么?

你有多种选择:then只是一个函数,所以你可以只使用(.then ..)。 如果 thenable 是一个 Promise 对象,promesa https://cljdoc.org/d/funcool/promesa/5.1.0/doc/user-guide 有一个很好的互操作故事。

在 promise 周围添加一些宏语法糖也非常简单,就像我在这里所做的那样: https://gist.github.com/beders/06eeb1d8f49de715c6bd2b84f634cff6

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

也简单翻译一下:

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

其中 on-midi-successon-midi-failure 是您在处理履行或拒绝承诺之前定义的一些函数。

所以基本上 .then 样式回调在 ClojureScript 中的处理方式与在 JavaScript.

中的处理方式完全相同