saab saab - 5 months ago 9
Node.js Question

Pass a block variable to a callback function that has already arguments

This is my callback:

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

}


This is my callback-user:

mysoapclient.invokeServiceMethod(jsonRecords,this.evaluateServiceResponse);


Here is the whole code. Inside
process
I create a block reference to my database:

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


The
invokeServiceMethod
talks to service then calls the callback passing it the service response.

How do I get the db reference into my callback
evaluateServiceResponse
?

Thanks.

Answer

Use closure :

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

And use like:

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