0

我在 CoffeeScript 类中有以下函数:

 use: (db, fn) ->
    fs.exists db, (exists) =>
      if exists?
        @db = db
        @_fetch()
      else
        fs.writeFile db, {}, (err) =>
          if err 
            err
          else 
            @db = db
            @_fetch()

困扰我的是我不得不写@db = db两次@_fetch()。我必须这样做的原因是else子句调用fs.writeFile它是异步的。因此,我不得不将这两行放在writeFile的回调中,以确保它们不会过早触发。

但是,有没有办法清理它并编写那些行?目前只有两行,但是如果回调存在10行呢?会很乱,不是吗?

也欢迎对这一小段代码提供任何其他反馈。不太确定错误处理(现在只是返回err..)。

4

3 回答 3

1

CoffeeScript has functions and => allows you to bind a function to an instance so why not just chop your code up into bound functions?

use: (db, fn) ->
  fetch = =>
    @db = db
    @_fetch()
  fs.exists db, (exists) =>
    if exists?
      fetch()
    else
      fs.writeFile db, {}, (err) =>
        if err 
          err
        else 
          fetch()

Then add whatever else (such as calling fn) needs to be done to fetch.

Also, I don't think your:

if err
  err

error handling does anything. I'm not a node.js expert but, AFAIK, writeFile doesn't care what the callback returns.

于 2013-08-04T18:05:04.657 回答
1

You can introduce a helper function:

use: (db, fn) ->
  helper = () =>
    @db = db
    @_fetch()
    …
    fn(null, result)

  fs.exists db, (exists) =>
    if exists
      helper()
    else
      fs.writeFile db, {}, (err) ->
        if err
          fn(err)
        else
          helper()
        return
    return
于 2013-08-04T18:06:54.417 回答
0

由于您不想加载数据库和获取的唯一时间是如果数据库不存在并且后续加载会产生错误,您可以尝试这样的事情......

use: (db, fn) ->
    fs.exists db, (exists) =>
    if not exists?
        fs.writeFile db, {}, (err) =>
            if err 
                return err

    @db = db
    @_fetch()
于 2013-08-04T18:10:45.593 回答