Last active
March 1, 2020 20:13
-
-
Save gonewest818/df6caeb90030c6890fbb7f5c7941e6a2 to your computer and use it in GitHub Desktop.
emacs-deferred dynamic chaining example
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
(require 'deferred) | |
(require 'request) | |
(setq xyzzy (deferred:$ | |
(deferred:next | |
(lambda () (message "test"))) | |
(deferred:nextc it | |
(lambda (x) (message "nextc: %s" x))))) | |
(setq plugh (deferred:$ | |
(deferred:nextc xyzzy ; note: not "it" but the previous deferred | |
(lambda (x) (message "chain: %s" x))) | |
(deferred:nextc it | |
(lambda (x) (message "chain2: %s" x))))) | |
;; eval up to this point and you get four messages in "*Messages*" | |
;; alternate experiment, we want to chain a rest API request whose | |
;; parameters are constructed from the value passed in from a previous | |
;; asynchronous call | |
(setq grue (deferred:$ | |
(deferred:nextc xyzzy ; note: not the anaphoric "it" | |
(lambda (x) ; x contains the value from xyzzy | |
(request-deferred | |
"http://worldtimeapi.org/api/ip" | |
:params `(("v" . ,x))))) ; use x as an api parameter | |
(deferred:nextc it | |
(lambda (response) | |
(pp (request-response-data response)))))) | |
(deferred-status grue) | |
;; using `request-deferred' (which is a MELPA package). | |
;; Here the `(deferred:new #'identity)' is used to | |
;; create a deferred which is NOT scheduled to execute, and | |
;; waits until the callback-post. The callback-post you can see | |
;; is invoked as the `:complete' callback for the request | |
;; and passes the reponse object as the value. thus any deferred | |
;; chained after this will execute when the url request is done. | |
(defun request-deferred (url &rest args) | |
(let* ((d (deferred:new #'identity)) | |
(callback-post (apply-partially | |
(lambda (d &rest args) | |
(deferred:callback-post | |
d (plist-get args :response))) | |
d))) | |
;; As `deferred:errorback-post' requires an error object to be | |
;; posted, use `deferred:callback-post' for success and error | |
;; cases. | |
(setq args (plist-put args :complete callback-post)) | |
(apply #'request url args) | |
d)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment