CoffeeScript - 我应该回电吗?

时间:2014-06-27 13:49:16

标签: javascript callback coffeescript

我正在研究这个简单的CoffeeScript类用于学习目的,我试图弄清楚我的'getMutant'方法是否应该有回调。代码似乎按原样运行,但在将来我想查询db或其他一些及时的异步事件。我怎么在这里写一个回调?

谢谢!

class Mutant
    @MutantArray: []

    constructor: (@name, @strength = 1, @agility = 1) ->
        @name = @name.toLowerCase(@name)
        Mutant.MutantArray.push(@)

    attack: (opponentName) ->
        opponentName = opponentName.toLowerCase(opponentName)

        # Should the method below have a callback since I'm using the result directly below?
        opponentExists = Mutant.getMutant(opponentName)

        if opponentExists then alert @name + " is attacking " + opponentName else alert "No Mutant by the name of '" + opponentName + "' found."

    @getAllMutants: () ->
        @MutantArray

    # Possibly need to add callback?
    @getMutant: (name) ->
        result = (mutant.name for mutant in Mutant.MutantArray when mutant.name is name)
        if result.length > 0 then mutant else null

Wolverine = new Mutant("Wolverine", 1, 2)
Rogue = new Mutant("Rogue", 5, 6)

Rogue.attack("Wolverine")

Mutant.getAllMutants()

1 个答案:

答案 0 :(得分:1)

这个问题有点基于意见,所以它可能会被低估。

但是,我会对它采取一些措施。如果您在代码之外有任何类型的后备存储,那么您必须在其中拥有一些异步处理程序 - 无论何时进入网络/ IO /数据库,您都将进行异步操作。我认为将getAllMutants放入Mutant课程中并不正确。我将一些现有代码改编为MongoDB中的getAllMutants函数。

getAllMutants: (onError, onSuccess) =>
  MongoClient.connect @config.dbUrl, (err, db) =>
    if err?
      onError("Failed: #{JSON.stringify err}")
    else
      collection = db.collection(@config.collection)
      collection.find().toArray( (err, mutants) ->
        if err?
          onError(err)
        else
          unless mutants?
            onError("No mutants object found")
          unless mutants.length?
            onError("No mutants object returned or not an array")
          else
            onSuccess(mutants)
            db.close()
      )