1 | ;; http://lispyscript.com
|
2 | ;; LispyScript sequenced callback example
|
3 | ;; No need for nested callbacks. Just write your callbacks in a sequence and pass "(next)" as
|
4 | ;; your callback, which will set the next function in the sequence as your callback.
|
5 | ;;
|
6 | ;; This example is a simple node server that will serve static plain text file to the browser.
|
7 | ;;
|
8 |
|
9 | (var fs (require "fs"))
|
10 | (var http (require "http"))
|
11 |
|
12 | (sequence requestHandler (request response)
|
13 |
|
14 | ( (var filename null)
|
15 | (if (= request.url "/")
|
16 | (set filename "index.html")
|
17 | (set filename (request.url.substr 1)))
|
18 | (response.setHeader "Content-Type" "text/html"))
|
19 |
|
20 | (function ()
|
21 | (fs.exists filename (next)))
|
22 |
|
23 | (function (exists)
|
24 | (if exists
|
25 | (fs.readFile filename "utf8" (next))
|
26 | (response.end "File Not Found")))
|
27 |
|
28 | (function (err data)
|
29 | (if err
|
30 | (response.end "Internal Server Error")
|
31 | (response.end data))))
|
32 |
|
33 | (var server (http.createServer requestHandler))
|
34 | (server.listen 3000 "127.0.0.1")
|
35 | (console.log "Server running at http://127.0.0.1:3000/")
|
36 |
|
37 |
|
38 | ;; A sequence expression creates a function. The arguments are
|
39 | ;; 1. The name for the function
|
40 | ;; 2. The parameters definition for the function
|
41 | ;; 3. A block of expressions to initialize the function.
|
42 | ;; 4. The rest are a sequence of functions to be called in order.
|
43 | ;; The sequence functions are defined in the scope of the sequence.
|
44 | ;; All parameters and initialised variables are visible to all the sequence functions.
|
45 | ;; Also visible to all the sequence functions is a function called next.
|
46 | ;; next returns the next function in the sequence.
|
47 |
|
48 | ;; In the example above we create a sequence function called requestHandler and
|
49 | ;; set it as the request callback for the node server.
|
50 | ;; In the initialization block we create a var called filename and set it to the
|
51 | ;; requested file. We also set the response content type.
|
52 | ;; There are three sequence functions and the first one ia called automatically when the
|
53 | ;; request handler function is called. It in turn calls fs.exists with the filename and
|
54 | ;; and sets the callback to "(next)". Which in this case is the second function in
|
55 | ;; the sequence.
|
56 | ;; The second function is the callback for the first, and it in turn calls fs.readFile
|
57 | ;; and passes the thirst function (next) as the callback. Since the third function
|
58 | ;; (callback for the second) does not call (next) the sequence ends there.
|
59 |
|
60 |
|
\ | No newline at end of file |