I'm trying to implement communication with coap server by using coap package. My goal is to get response (in coap.request()
response
event handler) and then pass it to other variables and functions.
Event:
'response'
function (response) { }
Emitted when a
response
is received. response is an instance ofIncomingMessage
.If the
observe
flag is specified, the'response'
event will return an instance ofObserveReadStream
. Which represent the updates coming from the server, according to the observe spec.
I've created class someClass
, which contains serverRequest()
method.
Method serverRequest()
takes mandatory options argument (which sets request options for coap.request()
) and optional argument which sets message body if needed. Purpose of this method is to send a request to server and return response
, which is instance of coap.IncomingMessage
.
const coap = require('coap');
class someClass {
constructor(someOption) {
this.someOption = someOption;
}
serverRequest(options, messageBody=undefined) {
const request = coap.request(options);
let response;
request.on('response', res => {
console.log(response); // undefined
response = res;
console.log(response); // valid response
});
if (messageBody !== undefined) {
request.write(messageBody);
}
request.end();
console.log(response); // undefined
return response;
}
}
I send message and obtain response successfully, however response
variable inside anonymous function seems to be unique and different from response
variable inside serverRequest
method.
Question: How can I pass variables from anonymous functions to other scopes?