如何在clojurescript中使用javascript promise?

问题描述 投票:0回答:1

我对js promises有疑问:我正在尝试转换此js代码:

stripe.createToken(card).then(function(result) {
    if (result.error) {
      // Inform the customer that there was an error.
      var errorElement = document.getElementById('card-errors');
      errorElement.textContent = result.error.message;
    } else {
      // Send the token to your server.
      stripeTokenHandler(result.token);
    }

我有以下内容:

(go
     (let [result (<!
                   (.createToken stripe @(subscribe [:card-element]))
                   )]
       (prn "result is" result)
       ;; (if (.-error result)
       ;;   (.textContent (js/document.getElementById "card-errors") (.-message .-error result))
       ;;   (prn "response is" (js/stripeTokenHandler (.-token result)))
       ;;   )
       )
    )

但是我得到“没有为类型对象定义任何协议方法ReadPort.take!:[对象承诺]”

我如何处理cljs中的js .then()部分?

interop clojurescript
1个回答
0
投票

似乎您对JavaScript互操作有些困惑。您可以在Cheatsheet部分下查看JavaScript Interop

这里有一些简单的例子:

JS                            CLJS

object.method(arg1, arg2) <=> (.method object arg1 arg2)
object.field              <=> (.-field object)
object.field = "foo"      <=> (set! (.-field object) "foo")
object.nested.field       <=> (.-field (.-nested object))

为了提高可读性,您可以使用-> arrow macro

->

然后您可以将示例重写为:

object.nested.field       <=> (-> object .-nested .-field)
© www.soinside.com 2019 - 2024. All rights reserved.