Created
December 17, 2023 08:11
-
-
Save chr15m/c5f943b6aa2c6089c04f04897b3cef81 to your computer and use it in GitHub Desktop.
Run a promise returning function over a sequence sequentially
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns promises | |
{:clj-kondo/config '{:lint-as {promsea.core/let clojure.core/let | |
promesa.core/doseq clojure.core/doseq | |
promesa.core/loop clojure.core/loop | |
promesa.core/recur clojure.core/recur}}} | |
(:require [promesa.core :as p])) | |
(def panel-choices [1 2 3 4 5]) | |
; simple test function returns a promise with doubled input | |
; after waiting a random amount of time | |
(defn something-returning-promise | |
[choice] | |
(print "started" choice) | |
(p/do! | |
(p/delay (* (js/Math.random) 1000)) | |
(print "done" choice) | |
(* 2 choice))) | |
(p/do! | |
; will return the last computation only and run sequentially | |
(print "--> doseq strategy") | |
(p/let [result | |
(p/doseq [panel-choice panel-choices] | |
(something-returning-promise panel-choice))] | |
(print "RESULT doseq" result "\n")) | |
; will run all computations in parallel and return an array of results | |
(print "--> map strategy") | |
(p/let [result | |
(p/all (mapv something-returning-promise panel-choices))] | |
(print "RESULT map" result "\n")) | |
; will run the computations sequentially one after another and return a vec of results | |
(print "--> reduce strategy") | |
(p/let [result | |
(p/all | |
(reduce | |
(fn [col panel-choice] | |
(conj col | |
(p/let [_ (last col)] | |
(something-returning-promise panel-choice)))) | |
[] | |
panel-choices))] | |
(print "RESULT reduce" result "\n")) | |
; will run the computations sequentially one after another and return a vec of results | |
(print "--> loop/recur strategy") | |
(p/let [result | |
(p/loop [choices panel-choices results []] | |
(if (empty? choices) | |
results | |
(p/let [result (something-returning-promise | |
(first choices))] | |
(p/recur (rest choices) | |
(conj results result)))))] | |
(print "RESULT loop/recur" result "\n"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment