summaryrefslogtreecommitdiff
path: root/tests/examplefiles/example.kal
blob: c05c14ca2c1ee5f87ece70b6ce662468fa8007a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env kal

# This demo executes GET requests in parallel and in series
# using `for` loops and `wait for` statements.

# Notice how the serial GET requests always return in order
# and take longer in total. Parallel requests come back in
# order of receipt.

http = require 'http'

urls = ['http://www.google.com'
        'http://www.apple.com'
        'http://www.microsoft.com'
        'http://www.nodejs.org'
        'http://www.yahoo.com']

# This function does a GET request for each URL in series
# It will wait for a response from each request before moving on
# to the next request. Notice the output will be in the same order as the
# urls variable every time regardless of response time.
# It is a task rather than a function because it is called asynchronously
# This allows us to use `return` to implicitly call back
task series_demo()
  # The `series` keyword is optional here (for loops are serial by default)
  total_time = 0

  for series url in urls
    timer = new Date

    # we use the `safe` keyword because get is a "nonstandard" task
    # that does not call back with an error argument
    safe wait for response from http.get url

    delay = new Date() - timer
    total_time += delay

    print "GET #{url} - #{response.statusCode} - #{response.connection.bytesRead} bytes - #{delay} ms"

  # because we are in a task rather than a function, this actually exectutes a callback
  return total_time

# This function does a GET request for each URL in parallel
# It will NOT wait for a response from each request before moving on
# to the next request. Notice the output will be determined by the order in which
# the requests complete!
task parallel_demo()
  total_time = 0

  # The `parallel` keyword is only meaningful here because the loop contains
  # a `wait for` statement (meaning callbacks are used)
  for parallel url in urls
    timer = new Date

    # we use the `safe` keyword because get is a "nonstandard" task
    # that does not call back with an error argument
    safe wait for response from http.get url

    delay = new Date() - timer
    total_time += delay

    print "GET #{url} - #{response.statusCode} - #{response.connection.bytesRead} bytes - #{delay}ms"

  # because we are in a task rather than a function, this actually exectutes a callback
  return total_time

print 'Series Requests...'
wait for time1 from series_demo()
print "Total duration #{time1}ms"

print ''

print 'Parallel Requests...'
wait for time2 from parallel_demo()
print "Total duration #{time2}ms"