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.open((err, db)->
unless err
db.createCollection('test', (err, collection)->
unless err
collection.find().toArray((err, items)->
unless err
//here how to return *items*
console.log(items)
)
)
)
Since the DB related operations are all asynchronous, you should specify a callback function for the find
routine.
(Sidenote:
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) ->
db.open (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) // <<<================
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) ->
db.open (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