从承诺中返回回调的结果

时间:2018-06-15 10:17:08

标签: javascript node.js callback promise

我尝试在类中创建通用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
})

1 个答案:

答案 0 :(得分:2)

你可以用诺言来实现它。通过承诺链,它可以解决。

request = (uri, xml) => {

      return new Promise((resolve, reject) => {

        rp
          .post(options)
          .then(response => {
            return parser.parseString(response.body, (err, result) => {

              resolve(JSON.stringify(result))
            })
          })
          .catch(err => {
            reject(err)
          })

      });
    }
相关问题