I try to make a universal request
method in a class.
It should be the central place to make requests to the API, get back results (in XML format), parse the result to JSON, and take care of error handling.
For parsing I use node-xml2js, what works with a callback.
How should I return the result from the callback, so after calling the function token I can work with JSON ?
Now it return some weird result (probably the parser.parseString()
)
{
comment: '',
sgmlDecl: '',
textNode: '',
tagName: '',
doctype: '',
procInstName: '',
procInstBody: '',
entity: '',
attribName: ''
}
Here is the code:
class Foo {
token(){
// ...
return this.request(uri, xml)
}
request(uri, xml) {
// ...
return rp.post(options).then(response=>{
return parser.parseString(response.body, (err, result) => {
// I can see the correct JSON result in the console
console.log(JSON.stringify(result))
return JSON.stringify(result)
})
}).catch(err=>{
console.log(err)
})
}
}
// usage
const foo = new Foo()
foo.token().then(res => {
console.log(res) // no result
})