简体   繁体   English

关于回调的Coffescript和Node.js编码风格

[英]Coffescript and Nodejs coding style regarding callbacks

Let's get to the point. 让我们说清楚。 I love CS, I love node and I'm more than fine using callbacks as the Gods have suggested. 我喜欢CS,也喜欢节点,并且像众神建议的那样,使用回调函数比我还好。

Unfortunately I usually end up constantly checking for errors in slightly nested callbacks. 不幸的是,我通常最终会不断检查轻微嵌套的回调中的错误。

Below are three different styles to accomplish the same sample task. 下面是完成同一示例任务的三种不同样式。 Which would be the one to use to avoid indentation and condition hell and at the same time not sacrifice on readability? 哪一个可以用来避免缩进和限制地狱,同时又不牺牲可读性?

Please feel free to suggest a new one if not using promises, async or iced-cs. 如果不使用promises,async或ice-cs,请随时提出一个新建议。

authenticate: (token, cb) =>
  @collection 'services', (err, collection) =>
    if err
      cb err, undefined
    else
      collection.findOne token: token, (errFindingService, service) =>
        if err
          cb errFindingService, undefined
        else
          cb undefined, service

authenticate: (token, cb) =>
  @collection 'services', (err, collection) =>
    if not err
      collection.findOne token: token, (errFindingService, service) =>
        if not errFindingService
          cb undefined, service
        else
          cb errFindingService, undefined
    else
      cb err, undefined

authenticate: (token, cb) =>
  @collection 'services', (err, collection) =>
    return cb err, undefined if err
    collection.findOne token: token, (errFindingService, service) =>
      return cb errFindingService, undefined if err
      cb undefined, service

PS: On the second one I'm using if not err instead of unless to conform with https://github.com/polarmobile/coffeescript-style-guide PS:在第二个中,我使用的是if not errunless符合https://github.com/polarmobile/coffeescript-style-guide

Thank you all in advance. 谢谢大家。 ^_^ ^ _ ^

My preferred boilerplate for error handling in CoffeeScript is return callback error if error . 我在CoffeeScript中处理错误的首选样板是error时return callback error if error So 所以

queryDb conditions, (error, results) ->
  return callback error if error
  console.log result for result in results
  • it's a 1-liner 这是1班轮
  • I strongly prefer error handling to always be at the top and to short-circuit the logic with return 我强烈希望错误处理始终位于最顶端,并通过return使逻辑短路
  • this leaves the success code at the same indentation level, as opposed to do an if/else 这使得成功代码处于相同的缩进级别,而不是if/else

The first one is closer to what nodejs uses internally, for example in the fs module. 第一个更接近于nodejs内部使用的东西,例如在fs模块中。

err is the first argument, so it makes sense to check it first. err是第一个参数,因此首先检查它是有意义的。 Once that it out of the way, it 'drills down' deeper into the callback stack. 一旦解决了它,它就会“深入”到回调堆栈中。

The first and third options compile to the same JS, except for the explicit return. 第一个和第三个选项编译为相同的JS,除了显式返回。

Which is easier to read and identify the essential pieces? 哪个更容易阅读和识别基本内容? Think about reviewing the code a couple of months from now. 考虑从现在开始几个月后再检查代码。

Coming from a Python background, I prefer to use a more open structure (eg the first), unless a more compact form is clearer. 来自Python背景,我更喜欢使用更开放的结构(例如第一个结构),除非更紧凑的形式更清晰。 So while I like Coffeescript comprehensions, I am less enamored with expressions that omit all possible {} and () . 因此,尽管我喜欢Coffeescript理解,但是却对那些省略了所有可能的{}()表达式感到迷恋。 If I have to stop and mentally add those back in, the conciseness has gone too far. 如果我必须停下来并在精神上重新添加这些内容,那么简洁性就太过分了。

Using flat-flow it can look something like this: 使用扁平流可以看起来像这样:

{ flow } = require 'flat-flow' 

authenticate: (token, done) ->
  flow { getCollection: @collection }, [

    # Get collection.
    (done) ->
      @getCollection 'services', (err, collection) ->
        done err, { collection }

    # Get service
    (done) ->
      @collection.findOne { token }, (err, service) ->
        done err, { service }

    # # Get service (alternative)
    # (done, { collection }) ->
    #   collection.findOne { token }, (err, service) ->
    #     done err, { service }

  ], (err, { service }) ->
    done err, service

    # You can use @service as well.

It's still clean on long call chains (with or without conditionals). 在长呼叫链(带或不带条件)上,它仍然是干净的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM