Please review the code below and suggest more elegant ways of doing the same.
I am storing JSON strings in Redis database. To extract an array of objects, I use the following code that works. Just for learning though I wanted to find better ways of doing the same. Here is the CoffeeScript code:
redis = require "redis"
client = module.exports.client = redis.createClient()
getRecord = module.exports.getRecord = (key, fn) ->
client.get key, (err, result) ->
fn err, null if err
obj = JSON.parse(result)
fn null, obj
getDataSet = module.exports.getDataSet = (pattern, fn) ->
开发者_运维知识库 client.keys pattern, (err, result) ->
fn err, null if err
dataSet = []
length = result.length
count = 0
for key in result
getRecord key, (err, obj) ->
fn err, null if err
count = count + 1
dataSet.push obj
fn null, dataSet if count is length
I think your code is pretty solid. Just be warned that your
for key in result
loop is creating a list comprehension; that means that if result.length
is large, you're going to see significant performance overhead and perhaps even memory issues. To avoid this, you need to add an explicit return
:
for key in result
getRecord key, (err, obj) ->
...
return
There was a proposal to introduce a void function syntax for just such cases, but none of CoffeeScript's core committers seem very fond of it.
精彩评论