更好的方法来检查coffeescript中的最后一个元素?

时间:2015-12-30 12:21:19

标签: javascript coffeescript

我想这样做:检查是否提供了callback,所以我按照以下步骤操作。我想知道的是:

  1. 我可以检查最后一个元素吗?
  2. 实际上在某些情况下可能会失败:如果最后一个元素是函数但它不是callbak。
  3. 这是代码

    _deferred = Q.defer()
    [before..., last] = args
    if typeof last is 'function'
        args = before
        cb = last
    else
      cb = (err, results) ->
          if err?
              _deferred.reject(err)
          else
              _deferred.resolve(results)
    // ... other code
    

2 个答案:

答案 0 :(得分:0)

更短的版本是" split"函数参数列表中的参数:

fn = (args..., cb) ->
    _deferred = Q.defer()

    # if cb is a function, it gets assigned to callback
    # and we skip the following statements because not (true and true) == false
    if not (typeof cb is 'function' and callback = cb)
        # cb is not a function so it's just another arg
        args.push cb
        callback = (err, results) ->
            if err? then _deferred.reject(err) else _deferred.resolve(results)

    console.log args
    console.log callback.toSource() # Function.toSource() only works on Firefox
    # ... other code

fn 'arg1', 'arg2', 'arg3', () -> 'foo'

关于你的第二个问题,只有你知道什么是真实的"回调是否。如果您无法按类型确定,则可以更改fn参数格式,例如,传递对象:

params =
    callback: () -> 'foo'
    args: [ 'arg1', 'arg2', 'arg3', () -> 'bar' ]

fn2 = ({ callback, args }) ->
    callback = callback or (err, results) ->
        if err? then _deferred.reject(err) else _deferred.resolve(results)

    console.log args
    console.log callback.toSource() # again, this only works in Firefox


fn2(params)

答案 1 :(得分:0)

Build Phases > Embed Frameworks