Last active
          March 27, 2025 05:13 
        
      - 
      
- 
        Save finalfantasia/e81a8fe812943edbc4b4392143fcff20 to your computer and use it in GitHub Desktop. 
    Schedule Jobs in Sequence with Promise in ClojureScript
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | (do | |
| (defn schedule-jobs-in-sequence | |
| "Schedules async `jobs` in sequence by using a JavaScript Promise chain." | |
| [jobs] | |
| (js/Promise. | |
| (fn [resolve reject] | |
| (let [init 42 | |
| results (atom [])] | |
| (loop [promise (.resolve js/Promise init) | |
| [job & more] jobs] | |
| (if job | |
| (recur (.then promise (fn [result] | |
| (when (not= result init) | |
| (swap! results conj result)) | |
| (job result))) | |
| more) | |
| (-> promise | |
| (.then (fn [result] | |
| (swap! results conj result) | |
| (resolve @results))) | |
| (.catch (fn [error] | |
| (reject error)))))))))) | |
| (defn make-job | |
| [n timeout] | |
| (fn [v] | |
| (js/Promise. | |
| (fn [resolve reject] | |
| (js/setTimeout (fn [] | |
| (.log js/console "v:" v "job:" n) | |
| (resolve n)) | |
| timeout))))) | |
| (-> (schedule-jobs-in-sequence | |
| (for [n (range 10)] | |
| (make-job n (* (rand-int n) 1000)))) | |
| (.then (fn [results] | |
| (.log js/console "results:" (clj->js results)))))) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment