Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird promise `promisifyAll` not working - cannot read property `then`

I am using a node module that uses the node callback convention. I wants to convert this module into an API using Bluebird promises. I am not getting how to do this.

Below is my node style callback function. I wants to convert it into thenable promise of bluebird.

var module = require('module'); // for example xml2js, or Mongoose
var parseString = xml2js.parseString; 
    parseString(xml, function (err, result) { // the regular API
      if (err) {
       console.log("Error in generation json from xml");
      } else {
       return result;
      }
    });

I tried this way using PromisifyAll but it is not working:

var module = Promise.promisifyAll(require('module')); // for example xml2js
xml2js.parseString(xml)
        .then(function (result) {
            console.log("result = ", result);
        })
        .catch(function (err) {
            console.err(err);
        });

I'm getting then is not a function errors. How can I fix it?

like image 510
Yogeshree Koyani Avatar asked May 06 '15 03:05

Yogeshree Koyani


1 Answers

When bluebird converts a module (like xml2js) into a promise based API using promisifyAll then it appends an Async suffix to each function name and adds that function into that object:

var xml2js = Promise.promisifyAll(require('xml2js')); // example: xml2js 
xml2js.parseStringAsync(xml) // NOTE THE ASYNC SUFFIX
        .then(function (result) {
            console.log("result = " + JSON.stringify(result));
        })
        .catch(function (err) {
            console.err(err);
        });

When you call parseString without the async suffix, it calls the original callback-based function.

like image 133
Yogeshree Koyani Avatar answered Oct 08 '22 06:10

Yogeshree Koyani