代码之家  ›  专栏  ›  技术社区  ›  Issac Howard

理解回调和递归中的参数

  •  0
  • Issac Howard  · 技术社区  · 2 年前

    我目前正在阅读Marijn Haverbeke的Eloquent JavaScript,其中有一段代码我希望有人能为我解释。请考虑以下注释代码:

    class Network {
       constructor() {
     // irrelevent code except the following line
     this.types = Object.create(null)
    }
    
       defineRequestType(name, handler) {
            this.types[name] = handler
          }
    }
    
    // when we call the defineRequestType method in another module.
    
    
    defineRequestType("note", (nest, content, source, done) => {
        // this is the callback I am referring to. (See below)
        console.log(`${nest.name} received note: ${content}`);  
        done(); 
      });
    
    // last but not least, the send method
    
    send(to, type, message, callback) {
            let toNode = this[$network].nodes[to]
            let handler = this[$network].types[type] // this is important. we're referring to the function's callback that we just called, and this callback is our handler
            if (!handler) // not important
              return callback(new Error("Unknown request type " + type))
            if (Math.random() > 0.03) setTimeout(() => {
              try {
                     /*
                        When we call the send method, the part that I don't understand is that we passed 'done()' as a callback to the handler. 
                        However, as you can see in the previous function call, done() does not take any arguments. 
                        Yet, the handler expects the callback of the handler to have 2 arguments 'error' and 'response'. How is this possible?
                     */
                handler(toNode, ser(message), this.name, (error, response) => {
                  setTimeout(() => callback(error, ser(response)), 10)
                })
              } catch(e) {
                callback(e)
              }
            }, 10 + Math.floor(Math.random() * 10))
          }
    
    
    

    如果你有兴趣阅读源代码,请看一下这个链接,你会发现上面的函数和更多(相当复杂)的函数。请点击乌鸦科技和第11章查看完整的代码。(如有要求)。

    Eloquent JavaScript

    0 回复  |  直到 2 年前