async.series使用胖箭头或自引用控制流错误

时间:2013-01-20 15:33:15

标签: javascript asynchronous coffeescript

我在类中使用异步库并在其中一个系列步骤中使用胖箭头导致两个回调被触发,其中带有胖箭头的函数直接调用结束步骤而不是下一步骤系列。为什么是这样?这是一个简化的例子。

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) ->

为什么会出现这种错误,是否有更好的方法来引用类方法而不是搞乱异步的控制流?

1 个答案:

答案 0 :(得分:0)

要检查的几件事情;

您对“更新”方法的定义不使用胖箭头,因此您需要确保该方法在调用时始终具有正确的“this”。通常,您会将此识别为someinstance.update(...)调用。

您是否完全确定您的代码不会触发对update方法的两次调用?您可以在方法的开头添加console.log以确保。

您的错误处理也看起来有点时髦,您可能希望稍微缩小示例,以确保它的行为符合您的要求。