我想这样做:检查是否提供了callback
,所以我按照以下步骤操作。我想知道的是:
这是代码
_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
答案 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