如何结合promesa与alts!将回调地狱转换为通道风格

解读

国内 Clojure 岗位集中在支付、广告、实时风控等高并发业务,面试常把“回调地狱”作为切入口,考察候选人能否用 Clojure 的并发原语写出可维护的异步代码。
promesa(Promise 库)提供 then/catch 链式调用,core.async 的 alts! 可以同时等待多个通道。二者结合的核心思路是:

  1. 把 Node/Java 异步回调包成 promesa 的 Promise;
  2. 把 Promise 结果投递到 core.async 通道;
  3. 用 alts! 做“谁先完成就取谁”的竞赛,彻底消灭嵌套回调。
    面试官希望听到:
  • 为什么不用回调而用通道(控制反转、背压、超时统一);
  • 如何防止 goroutine 泄漏(close!、promise->ch 的单次投递);
  • 异常怎样穿透(promise 的 catch 分支要往通道里送异常对象,alts! 拿到后统一处理)。

知识点

  1. promesa 基本模型:p/resolved、p/rejected、p/then、p/catch。
  2. core.async 通道与 go 块:>!、<!、alts!、timeout。
  3. 回调转 Promise:p/create 或 promesa.core/deferred。
  4. Promise 转通道:go 块里 <! 会阻塞,因此要在 Promise 回调里用 put! 把值推入通道;为防内存泄漏,用 promise->ch 工具函数一次性 close!。
  5. alts! 的优先级与竞态:返回 [value port],可用 :priority true 让先写的通道优先。
  6. 异常通道模式:单独建一个 err-ch,所有异常都 >! 到 err-ch,业务逻辑用 alts! 同时监听正常 ch 与 err-ch,实现“要么成功要么异常”的统一处理。
  7. 资源释放:finally 块或 go 块的 (close! ch) 保证无论成功失败都关闭通道,避免 go 块挂起。

答案

(ns demo.async
  (:require [promesa.core :as p]
            [clojure.core.async :refer [go chan <! >! close! alts! timeout go-loop]]))

;; 工具:把任意 Promise 转成一次性通道
(defn promise->ch [p]
  (let [ch (chan 1)]
    (-> p
        (p/then (fn [v] (go (>! ch {:ok v})) (close! ch)))
        (p/catch (fn [e] (go (>! ch {:error e})) (close! ch))))
    ch))

;; 模拟三个外部服务,返回 Promise
(defn fetch-user [id] (p/delay 100 {:id id :name "kim"}))
(defn fetch-order [user-id] (p/delay 150 {:order-id 200 :total 99}))
(defn fetch-coupon [user-id] (p/delay 80 {:coupon "SAVE20"}))

;; 业务:任意一个服务失败或 200ms 超时都算失败
(defn user-page [user-id]
  (go
    (let [user-ch   (promise->ch (fetch-user user-id))
          order-ch  (promise->ch (fetch-order user-id))
          coupon-ch (promise->ch (fetch-coupon user-id))
          tout-ch   (timeout 200)
          [v port]  (alts! [user-ch order-ch coupon-ch tout-ch])]
      (cond
        (= port tout-ch)         {:status 500 :body "timeout"}
        (:error v)               {:status 500 :body (:error v)}
        :else                    {:status 200
                                  :body (select-keys v [:id :order-id :coupon])}))))

;; REPL 测试
(go (println (<! (user-page 1))))
;; => {:status 200, :body {:id 1, :order-id 200, :coupon "SAVE20"}}

要点讲解:

  1. promise->ch 把三个异步 IO 全部变成通道,主流程只剩一个 alts!,消灭嵌套。
  2. 超时通道 tout-ch 也参与 alts!,统一处理 SLA。
  3. 异常和超时都走同一条返回路径,外部调用者只需判断 status,无需再写回调。

拓展思考

  1. 批量竞态:如果服务返回的是列表,可把每个元素再包成通道,用 alts! 做“最快 N 个”聚合,常见于广告竞价。
  2. 背压控制:promise->ch 里用 (chan 1) 而非 (chan),防止 Promise 侧生产过快把内存打爆;若下游消费慢,可改用 sliding-buffer 或 dropping-buffer。
  3. 与 manifold 对比:国内也有团队用 manifold/streams,面试时可谈“core.async 是 CSP 模型,manifold 是 Reactive 模型”,根据场景选型。
  4. 类型安全:大型项目可引入 clojure.spec 对通道里的 {:ok v} {:error e} 做运行时校验,降低通道协议口头约定带来的 BUG。