-1

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
})
hong4rc
  • 3,999
  • 4
  • 21
  • 40
user3568719
  • 1,036
  • 15
  • 33

1 Answers1

3

You can use promise to achieve it.Through promise chaining , it can be solve.

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)
          })

      });
    }
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
  • Promise chaining would be sensible. This, however, is an example of the [nested promises antipattern](http://taoofcode.net/promise-anti-patterns/) – Quentin Jun 15 '18 at 10:22
  • @Quentin even its anti-pattern but still its achieved using chaining – RIYAJ KHAN Jun 15 '18 at 10:25
  • @Quentin could you please show us your suggestion? Thanks – user3568719 Jun 15 '18 at 10:28
  • @user3568719 — There's a perfectly good duplicate question that explains how to work with callbacks. – Quentin Jun 15 '18 at 10:29
  • @RIYAJKHAN — No, it isn't. If you were chaining then, `request` would return a promise returned by the last `then` function, and not a promise created immediately inside `request` that was resolved by a function passed to a `then` inside it. – Quentin Jun 15 '18 at 10:35
  • @Quentin that question has 33 answers with jquery, async/await, angular, etc. For me it would be _much_ more easie to understand the problem on this example. But thanks for taking the time and copy paste the link here. – user3568719 Jun 15 '18 at 10:54