Skip to content

Commit

Permalink
Added a callback to the #submitTask function in the client.
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh Bassett committed Apr 6, 2012
1 parent 391d821 commit e1cd471
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/client.coffee
Expand Up @@ -3,7 +3,7 @@ zmq = require "zmq"
EventEmitter = require("events").EventEmitter

class Handle extends EventEmitter
constructor: (@id) ->
constructor: (@id, @callback) ->

# A client submits tasks to a broker.
module.exports = class Client
Expand All @@ -17,8 +17,8 @@ module.exports = class Client
# Submits a task with the given name and data.
#
# Returns a handle to the task.
submitTask: (name, data) ->
handle = @_addHandle()
submitTask: (name, data, callback) ->
handle = @_addHandle uuid(), callback
payload = JSON.stringify id: handle.id, request: name, data: data
@socket.send [new Buffer(""), payload]
handle
Expand Down Expand Up @@ -47,17 +47,19 @@ module.exports = class Client

_completed: (task) ->
handle = @_getHandle task.id
handle.callback null, task.data if handle.callback?
handle.emit "complete", task.data
@_removeHandle handle

_failed: (task) ->
handle = @_getHandle task.id
handle.callback task.data if handle.callback?
handle.emit "error", task.data unless handle.listeners("error").length is 0
@_removeHandle handle

_addHandle: ->
handle = new Handle uuid()
@handles[handle.id] = handle
_addHandle: (id, callback) ->
handle = new Handle id, callback
@handles[id] = handle
handle

_removeHandle: (handle) ->
Expand Down
20 changes: 20 additions & 0 deletions test/client_test.coffee
Expand Up @@ -32,6 +32,16 @@ describe "Client", ->
data.should.eql "lorem"
done()

it "should callback when a task failed", (done) ->
@socket.on "message", (payload) =>
task = JSON.parse payload
payload = JSON.stringify id: task.id, response: "failed", data: "lorem"
@socket.send payload
@client.submitTask "reverse", "hello", (error, data) ->
error.should.eql "lorem"
should.not.exist data
done()

it "should emit a complete event when a task is completed", (done) ->
@socket.on "message", (payload) =>
task = JSON.parse payload
Expand All @@ -41,3 +51,13 @@ describe "Client", ->
handle.on "complete", (data) ->
data.should.eql "elloh"
done()

it "should callback when a task is completed", (done) ->
@socket.on "message", (payload) =>
task = JSON.parse payload
payload = JSON.stringify id: task.id, response: "completed", data: "elloh"
@socket.send payload
@client.submitTask "reverse", "hello", (error, data) ->
should.not.exist error
data.should.eql "elloh"
done()

0 comments on commit e1cd471

Please sign in to comment.