Search code examples
node.jspromisebluebird

Promise bluebird with multiple classes response


Im trying to make request to url and parse XML data after that request and print result but I keep getting undefined instead of result, what I'm doing wrong?

var parseUrl = 'url which returns XML as response';
    var request = Promise.promisify(require("request"));
    var xml2js = Promise.promisify(require('xml2js').parseString);
    Promise.promisifyAll([request, xml2js]);

    request({url: parseUrl, json: true}).then(function(data){
        if (data.body){
            return data.body;
        } else {
            return error.throw('Failed to parse body from response');
        }
    }).then(function(data){
        xml2js(data, function(err, result){
            if (!err){
                return result;
            } else {
                return error.throw('Failed to read converted body from response');
            }
        });
    }).then(function(data){
        console.warn(data);
    }).catch(function(e){
        console.log(e.message);
    });

Solution

  • 1) Because xml2js already promisifiсation.

    2) You do not need to use Promise.promisifyAll

    var parseUrl = 'url which returns XML as response';
    var request = Promise.promisify(require("request"));
    var xml2js = Promise.promisify(require('xml2js').parseString);
    
    request({url: parseUrl, json: true})
      .then(function(data){
        if (data.body){
            return data.body;
        } else {
            return error.throw('Failed to parse body from response');
        }
    }).then(xml2js)
      .then(function(data){
        console.warn(data);
    }).catch(function(e){
        console.log(e.message);
    });