Skip to content

Instantly share code, notes, and snippets.

@scribu
Created November 24, 2012 03:21
Show Gist options
  • Select an option

  • Save scribu/4138227 to your computer and use it in GitHub Desktop.

Select an option

Save scribu/4138227 to your computer and use it in GitHub Desktop.
Implementation of concurrent query in CoffeeScript
# We have several database replicas and want to minimize latency by querying them
# all and returning the first response to arrive.
#
# http://concur.rspace.googlecode.com/hg/talk/concur.html#slide-54
class Connection
constructor: (@name) ->
query: (query, continuation) ->
@op = setTimeout(=>
continuation(@name)
null
, Math.floor(Math.random()*10000))
abort: ->
clearTimeout(@op)
do_query = (conns, query, continuation) ->
for conn in conns
conn.query(query, (result) ->
continuation(result)
for conn in conns
conn.abort()
null
)
task 'run', 'Run the thing.', (options) ->
conns = (new Connection(i) for i in [1..10])
do_query(conns, 'foobar', (result) ->
console.log("First connection to return was #{result}.")
)
@scribu
Copy link
Author

scribu commented Nov 24, 2012

Invocation:

$ cake run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment