0

Is there a concrete reason to prefer executing callbacks to functions before or after exiting the called function? Example

function doSomethingPossiblyAsync(callback) {
  if (errorDetectedImmediately) {

     // call callback immediately before doSomethingPossilbyAsync has returned
     callback(someError);
  }
  ...
}

vs

function doSomethingPossiblyAsync(callback) {
  if (errorDetectedImmediately) {

     // call callback after doSomethingPossiblyAsync has returned
     process.nextTick(function() {
       callback(someError);
     }
  }
  ...
}

I prefer the second because it makes it consistent with the asynciness of the non-error path but I have no idea if I'm being rational or if it doesn't matter.

Note that for EventEmttiers it matters since you can't add your listeners before you've created the object which means you shouldn't emit events until after creation even if detected during creation but does some similarly logical reason apply to callbacks?

  • Why are you using callbacks anyway? Promises are much better to handle asynchronous operations. – Michał Perłakowski May 6 '16 at 19:31
1

There are, as always, tradeoffs. Your first option is simpler, more efficient, and requires less memory. Your second provides a more consistent environment for callbacks to operate in.

Given the possibility of callback authors creating hard-to-identify bugs with the first option by assuming that their callback will be called asynchronously, I'd suggest using the second variant except in performance critical code.

-4

If you take a look at how things are done in jQuery, AngularJS, ES6, you will see that what they choose is none of what you did.

Instead they use 2 separate callbacks, one for success, one for error.

However i don't see any issue to not wait if an error is detect automatically.

  • 2
    This doesn't really answer the question asked. – Jules May 2 '16 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.