0

Is adding a callback to a event okay? Like so?

Client.prototype.send = function(data, cb) {
  // convert json to string
  data = JSON.stringify(data)
  this.client.write(data)

  // wait for the response of this request
  this.client.on('data', function(data) {
    var request = JSON.parse(data)

    // return response as callback
    if (request.type === data.type) {
      cb(request)
    }

  })

}

Then invoked like:

// send request and wait for reply
client.send(data, function(response) {
  // do stuff to reply/response

  // this executes +1 times for every sent request should only do 1 request 1 response
  console.log(response)
})

Do it do the callback every time the same type of event is emitted?
Does this make performance suffer?

1 Answer 1

1

You ask a couple of questions, let me try and answer them in order.

Is adding a callback to a event okay?

Sure, if you want a function to be called after an event then why not?

Do it do the callback every time the same type of event is emitted?

The way you have it written, cb will only be called if request.type === data.type

Does this make performance suffer?

That depends.

By just adding a parameter that is a function that gets called conditionally, you really won't have any appreciable difference in performance in the case where the function doesn't get called. Otherwise, it depends on the performance of your callback function.

In either case with a reasonable callback function I wouldn't expect it to be a cause of performance issues.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually something is happening. Everytime I make the event happen. it executes the callback +1 times. So if I did it 10 times. It executes 10 times. I only want it to do one per request. Some kind of request/response style.
I'm not clear as to what you want to have happen and what is happening. From what I can gather, you want more control over when the function is run? Maybe you should look into promises such as the jQuery deferred object
A question related to this: stackoverflow.com/questions/24409167/…. I'm marking this as answered as it did answer my questions here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.