Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Coffescript and Nodejs coding style regarding callbacks

Coffescript and Nodejs coding style regarding callbacks

Problem

Let's get to the point. I love CS, I love node and I'm more than fine using callbacks as the Gods have suggested.

Unfortunately I usually end up constantly checking for errors in slightly nested callbacks.

Below are three different styles to accomplish the same sample task. Which would be the one to use to avoid indentation and condition hell and at the same time not sacrifice on readability?

Please feel free to suggest a new one if not using promises, async or iced-cs.

authenticate: (token, cb) =>
  @collection 'services', (err, collection) =>
    if err
      cb err, undefined
    else
      collection.findOne token: token, (errFindingService, service) =>
        if err
          cb errFindingService, undefined
        else
          cb undefined, service

authenticate: (token, cb) =>
  @collection 'services', (err, collection) =>
    if not err
      collection.findOne token: token, (errFindingService, service) =>
        if not errFindingService
          cb undefined, service
        else
          cb errFindingService, undefined
    else
      cb err, undefined

authenticate: (token, cb) =>
  @collection 'services', (err, collection) =>
    return cb err, undefined if err
    collection.findOne token: token, (errFindingService, service) =>
      return cb errFindingService, undefined if err
      cb undefined, service

PS: On the second one I'm using if not err instead of unless to conform with https://github.com/polarmobile/coffeescript-style-guide

Thank you all in advance. ^_^

Problem courtesy of: George Antoniadis

Solution

My preferred boilerplate for error handling in CoffeeScript is return callback error if error. So

queryDb conditions, (error, results) ->
  return callback error if error
  console.log result for result in results
  • it's a 1-liner
  • I strongly prefer error handling to always be at the top and to short-circuit the logic with return
  • this leaves the success code at the same indentation level, as opposed to do an if/else
Solution courtesy of: Peter Lyons

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Coffescript and Nodejs coding style regarding callbacks

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×