Skip to content

Instantly share code, notes, and snippets.

@dvdsgl
Created February 12, 2012 15:19
Show Gist options
  • Save dvdsgl/1809026 to your computer and use it in GitHub Desktop.
Save dvdsgl/1809026 to your computer and use it in GitHub Desktop.
fs = require 'fs'
class MyClass
# Trying to create middleware with access to class members.
withData: (cb) ->
return cb @__data if @__data?
fs.readFile 'datafile.json', (err, json) =>
throw err if err?
@__data = JSON.parse json
cb @__data
getUsers: (n) -> @withData (data) =>
data.users[..n-1]
x = new MyClass
console.log x.getUsers 5
@tdreyno
Copy link

tdreyno commented Feb 12, 2012

Why so much magic? Why not just call withData from inside the function?

@dvdsgl
Copy link
Author

dvdsgl commented Feb 12, 2012

In my actual use case, I have many functions that rely on async data and I just wanted to avoid the extra level of indentation.

@dvdsgl
Copy link
Author

dvdsgl commented Feb 12, 2012

@tdreyno, I found a less magical version that works – it's just what you recommended except I call the 'middleware' right after the argument list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment