【问题标题】:Pass a block variable to a callback function that has already arguments将块变量传递给已经有参数的回调函数
【发布时间】:2016-06-29 09:26:27
【问题描述】:

这是我的回调:

function evaluateServiceResponse(err, response){
  db.answerCollection.insert({id: response["serviceAnswer"]["id"]}); //problem is this line

}

这是我的回调用户:

mysoapclient.invokeServiceMethod(jsonRecords,this.evaluateServiceResponse);

这是整个代码。在process 内部,我创建了一个对我的数据库的块引用:

process(function(){
  ...
  let db=null;
  db = mongoClient.connect(connectionURL); 
  //Do whatever to create jsonRecords
  mysoapclient.invokeServiceMethod(jsonRecords,this.evaluateServiceResponse);
  ...
});

invokeServiceMethod 与服务对话,然后调用回调将服务响应传递给它。

如何在我的回调evaluateServiceResponse 中获取数据库引用?

谢谢。

【问题讨论】:

    标签: node.js parameters callback arguments scoping


    【解决方案1】:

    使用闭包:

    function evaluateServiceResponse(db){ 
     return function(err, response){
      db.answerCollection.insert({id: response["serviceAnswer"]["id"]}); //problem is this line
    }
    }
    

    并像这样使用:

     mysoapclient.invokeServiceMethod(jsonRecords,this.evaluateServiceResponse(db));
    

    【讨论】:

    • 谢谢;这有帮助:)
    【解决方案2】:

    我相信这就是你想要的:

    function evaluateServiceResponse(err, response, db){
      db.answerCollection.insert({id: response["serviceAnswer"]["id"]}); //problem is this line
    }
    
    
    
    process(function(){
      let db=null;
      db = mongoClient.connect(connectionURL); 
      //Do whatever to create jsonRecords
      mysoapclient.invokeServiceMethod(jsonRecords, (err, response) => {
        return this.evaluateServiceResponse(err, response, db);
      });
    });
    

    【讨论】:

    • 此解决方案不正确。我认为“这个”。引用不能传输到回调的主体中。这就是为什么我在以下位置收到错误:TypeError: Cannot read property 'evaluateServiceResponse' of undefined"
    • @saab 你说得对。 function(err, response) 最初是箭头函数。无论如何,将修复原始代码。
    • 我不明白你的意思。这不是和以前一样的代码,只是使用了新的语法还是我混淆了什么?我的意思是即使在这里,“this”也是未定义的。
    • @saab 不。箭头函数有点不同——它们没有自己的this。查看 MDN:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target).
    • 好的,谢谢。我不知道箭头函数表达式。我想我得到了这个解决方案,因为它更易于阅读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2015-08-29
    • 2019-10-08
    相关资源
    最近更新 更多