【发布时间】:2012-02-05 06:47:15
【问题描述】:
我希望能够从此咖啡脚本代码重构错误处理:
# Do some stuff with 2 levels of asynchronous callbacks and error handling
vote = (res, data) ->
Case.findOne { caseId: data.id }, (err, mycase) ->
if err
console.error 'Vote failed'
else
myvote = new Vote
case: mycase._id
myvote.save (err) ->
if err
console.error 'Could not add vote'
else
console.log 'Success!'
到这样的事情:
# Run my function, do error handling, and run the callback if no error
runit = (func, arg, errmsg, callback) ->
func arg, (err, docs) ->
if err
console.log errmsg + ': ' + err
else
callback docs
# Original code, simplified
vote = (res, data) ->
runit Case.findOne { caseId: data.id }, 'Vote failed', (mycase) ->
myvote = new Vote
case: mycase._id
runit myvote.save, 'Could not add vote', () ->
console.log 'Success!'
显然,runit 函数需要能够正确处理一个或多个参数,我没有尝试正确编码。
如果我这样运行它,我会得到一个错误:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'findOne' of undefined
at /tmp/node_modules/mongoose/node_modules/hooks/hooks.js:27:28
at /tmp/lib/api.js:227:12
at Promise.<anonymous> (/tmp/lib/api.js:216:16)
at Promise.<anonymous> (/tmp/node_modules/mongoose/lib/promise.js:120:8)
at Promise.<anonymous> (events.js:67:17)
at Promise.emit (/tmp/node_modules/mongoose/lib/promise.js:59:38)
at Promise.complete (/tmp/node_modules/mongoose/lib/promise.js:70:20)
at /tmp/node_modules/mongoose/lib/query.js:885:15
at model.<anonymous> (/tmp/node_modules/mongoose/lib/document.js:181:5)
at model.init (/tmp/node_modules/mongoose/lib/model.js:181:36)
【问题讨论】:
-
node.js 中错误处理的永恒样板问题。在 SO 中搜索会给你一些关于这个问题的想法(如果他们让你满意是另一回事)。
-
我想你的意思是,
runit Case.findOne, { caseId: data.id }, 'Vote failed', (mycase) ->
标签: javascript node.js asynchronous callback coffeescript