node.js 中的常见做法是将错误消息作为回调函数的第一个参数返回。在纯 JS(Promise、Step、seq 等)中有许多解决方案可以解决这个问题,但它们似乎都不能与 ICS 集成。在不损失可读性的情况下处理错误的正确解决方案是什么?
例如:
# makes code hard to read and encourage duplication
await socket.get 'image id', defer err, id
if err # ...
await Image.findById id, defer err, image
if err # ...
await check_permissions user, image, defer err, permitted
if err # ...
# will only handle the last error
await
socket.get 'image id', defer err, id
Image.findById id, defer err, image
check_permissions user, image, defer err, permitted
if err # ...
# ugly, makes code more rigid
# no way to prevent execution of commands if the first one failed
await
socket.get 'image id', defer err1, id
Image.findById id, defer err2, image
check_permissions user, image, defer err3, permitted
if err1 || err2 || err3 # ...