gpt4 book ai didi

javascript - 带有回调和简化错误处理的 Coffeescript

转载 作者:搜寻专家 更新时间:2023-10-31 23:06:41 26 4
gpt4 key购买 nike

我希望能够从此 coffeescript 代码重构错误处理:

# 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)

最佳答案

# Run my function, do error handling, and run the callback if no error
runit = (func, args..., errmsg, callback) ->
func args..., (err, docs) ->
if err
return console.log errmsg + ': ' + err
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 编译成什么:

runit = function() {
var args, callback, errmsg, func, _i;
func = arguments[0], args = 4 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 2) : (_i = 1, []), errmsg = arguments[_i++], callback = arguments[_i++];
return func.apply(null, __slice.call(args).concat([function(err, docs) {
if (err) return console.log(errmsg + ': ' + err);
return callback(docs);
}]));
};

关于javascript - 带有回调和简化错误处理的 Coffeescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8776476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com