Javascript 使用fat箭头或自引用的async.series控制流错误
我在一个类中使用异步库,在一个系列步骤中使用一个胖箭头会触发两个回调,其中带有胖箭头的函数直接调用结束步骤,而不是系列中的下一个步骤。为什么会这样?这里是一个简化的例子Javascript 使用fat箭头或自引用的async.series控制流错误,javascript,asynchronous,coffeescript,Javascript,Asynchronous,Coffeescript,我在一个类中使用异步库,在一个系列步骤中使用一个胖箭头会触发两个回调,其中带有胖箭头的函数直接调用结束步骤,而不是系列中的下一个步骤。为什么会这样?这里是一个简化的例子 class FakeProfileRepository getByEmail : (email, callback) -> return callback null, email update : (data, callback) -> async.series
class FakeProfileRepository
getByEmail : (email, callback) ->
return callback null, email
update : (data, callback) ->
async.series
checkNull: (next) ->
if data and data.uname
next null
else
next Error("No profile to save")
checkEmailExists: (next) =>
@getByEmail 'test', (err, results) ->
if not results
next new Error("Could not find an existing profile to update")
else
next err
checkProfile: (next) ->
return next new Error('foo')
, (err, results) ->
console.log('series ended with error:' + err)
这会导致触发一个额外的回调,其中checkEmailExists触发它对最终结果函数的回调,以及checkProfile步骤(正确)触发最后一个结果函数
EXPECTED:
series ended with error:foo
ACTUAL: (two callbacks fired)
series ended with error:foo
series ended with error:null
如果我使用胖箭头,或者即使我设置self=This并使用普通箭头
checkEmailExists: (done) ->
self.getByEmail data.uname, (err, results) ->
为什么会发生这种错误,有没有更好的方法来引用类方法,而不是打乱异步的控制流?有几件事需要检查 您对“update”方法的定义没有使用fat箭头,因此您需要绝对确保该方法在调用时始终具有正确的“this”。通常,您会将其识别为someinstance.update(…)调用 您是否绝对确定您的代码不会触发对update方法的两个调用?您可以在方法的开头添加一个console.log来确保
您的错误处理看起来也有点古怪,您可能希望将示例缩小一点,以确保其完全按照您的意愿运行。通常从其他方法引用实例方法的最佳方式是什么?与您一样(例如@getByEmail),但由于您没有对update方法使用胖箭头,因此隐含的“this”可能不是你想要的。有关实例方法与类方法的更多信息,请参见: