使用 CoffeeScript 从 Node.js 上的 Redis 中提取对象数组的更好方法
请查看下面的代码并提出更优雅的方法来执行相同的操作。
我将 JSON 字符串存储在 Redis 数据库中。为了提取对象数组,我使用以下有效的代码。只是为了学习,尽管我想找到更好的方法来做同样的事情。这是 CoffeeScript 代码:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你的代码非常可靠。请注意,您的
循环正在创建列表理解;这意味着如果
result.length
很大,您将看到显着的性能开销,甚至可能出现内存问题。为了避免这种情况,您需要添加一个明确的返回
:有人提议引入一个void 函数语法 就适合这种情况,但 CoffeeScript 的核心提交者似乎都不太喜欢它。
I think your code is pretty solid. Just be warned that your
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 explicitreturn
: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.