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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With