Suggested duplicate does not sufficiently serve as an answer. link is better answer. And matches @deceze reply
I'm a convert to node from .net. Thus I'm loving the syntactic sugar provided by es6. I have run myself into a scoping problem during one of my complexity refactors.
I return my promises from inside classes. I refactored a little of PolicyMapper.mapDao()
code into another class function (mapJSONtoDAO
). Unit testing has no problem with this. The problem occurs during chaining with other promises. this.mapJSONtoDAO()
becomes undefined.
route.js ->
const policyService = new PolicyService();
const policyMapper = new PolicyMapper();
const policyMapPromise = policyService.getPolicy(req.body.policyNumber, office)
.then(policyMapper.mapDao, next);
PolicyMapper class ->
class PolicyMapper {
mapDao(soapResponse) {
return new Promise((resolve, reject) => {
xml2js.parseString(soapResponse[config.responseProperty], {}, (error, json) => {
resolve(this.mapJSONtoDAO(json));
});
});
}
mapJSONtoDAO(json) {
let policyDAO = new PolicyDAO();
policyDAO.givenName = json["policy-response"]["given-name"]
return policyDAO;
}
}
The below refactor of the route.js protects scope association between class and promise. Is there an simplier way to inplement this. I really want my code to be simple for any engineer maintaining my code.
const policyService = new PolicyService();
const policyMapper = new PolicyMapper();
const policyMapPromise = policyService.getPolicy(req.body.policyNumber, office)
.then((soapResponse) => {
return policyMapper.mapDao(soapResponse)
}, next);