how to return a value for a function in coffee-script


I used coffee-script to write node.js, it works fine, what i want to know is how to return a value for a function in coffee-script, here is my code

exports.find=->, db)->
        unless err
            db.createCollection('test', (err, collection)-> 
                unless err
                    collection.find().toArray((err, items)->
                        unless err
                           //here how to return *items*
Problem courtesy of: Mil0r


Since the DB related operations are all asynchronous, you should specify a callback function for the find routine.


you should use guard clauses like return if err instead of unless err. It decreases the indentation level and makes the code easier to read.

Or better yet, you should pass the error to the callback as the first parameter. This is the convention for node.js projects)

exports.find = (callback) -> (err, db) ->
    return callback(err) if err
    db.createCollection 'test', (err, collection) ->
      return callback(err) if err
      collection.find().toArray (err, items) ->
        return callback(err) if err
        callback(null, items) // <<<================ 
Solution courtesy of: qiao


I would use flow control such as async which let you to have cleaner code and easy to understand async flows

npm install async

async = require "async"

exports.find = (callback) ->
  async.waterfall [
    (callback) -> (err, db) -> callback err, db

    (db, callback) ->
      db.createCollection 'test', (err, collection) -> callback err, collection

    (collection, callback) ->
      collection.find().toArray (err, items) -> callback err, items
  ], (err, items) ->
    if err then callback null else callback items

In this case, when error occurred null will be returned.

If there is no error, items will be returned

Discussion courtesy of: InspiredJW

This recipe can be found in it's original form on Stack Over Flow.