0

In the code here the first example just does callbacks, the second example does "return callback".

Under what circumstances should I do "return callback" instead of just "callback"?

this.listRegions((err, regions) => {
  if (err) {
    callback(err)
  } else {
    callback(null, regions)
  }
})

OR

this.listRegions((err, regions) => {
  if (err) {
    return(callback(err))
  } else {
    return(callback(null, regions))
  }
})
Duke Dougal
  • 24,359
  • 31
  • 91
  • 123
  • http://stackoverflow.com/questions/483073/getting-a-better-understanding-of-callback-functions-in-javascript – Craig Selbert Feb 27 '16 at 03:40
  • 2
    You return something whenever you expect a value from a function call. – Sebastian Simon Feb 27 '16 at 03:40
  • This question has already been asked and answered, but I cannot track it down now. The simple answer is (usually) "no". You can use `return` in order to get out of the function, though, as a kind of shorthand for `callback(null, regions); return`. For instance, in the second sample code you show, this would allow you to eliminate the `else` part. BTW, the parens are not required around the return value and many popular style guides call for you not to use them. –  Feb 27 '16 at 03:49

1 Answers1

0

It's useful to break out from the function earlier, without extra braces and conditional statements:

this.listRegions((err, regions) => {
  if (err)
    return callback(err)
  callback(null, regions)
})
Afanasii Kurakin
  • 3,330
  • 2
  • 24
  • 26