【发布时间】:2018-06-15 18:23:17
【问题描述】:
我尝试在一个类中创建一个通用的request 方法。
它应该是向 API 发出请求、返回结果(以 XML 格式)、将结果解析为 JSON 以及处理错误处理的中心位置。
我使用node-xml2js 进行解析,这适用于回调。
我应该如何从回调中返回结果,以便在调用函数令牌后我可以使用 JSON ?
现在它返回一些奇怪的结果(可能是parser.parseString())
{
comment: '',
sgmlDecl: '',
textNode: '',
tagName: '',
doctype: '',
procInstName: '',
procInstBody: '',
entity: '',
attribName: ''
}
代码如下:
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
})
【问题讨论】:
-
你没有从承诺中返回,你在
then做的事情。
标签: javascript node.js callback promise