I want to return the data once it has been processed by convertToHtml, but it just return the data before the converting process is over. Any suggestions on how to implement it?
exports.extractData = async function(path) {
var mammoth = require("mammoth");
return await mammoth.convertToHtml({path: path}, options)
.then(function(result) {
var html = result.value;
var messages = result.messages;
return html;
}
}
Based on the suggestion I changed to:
exports.extractData = async function(path) {
var mammoth = require("mammoth");
const aux = await mammoth.convertToHtml({path: path}, options);
return aux.value;
}
}
Yet, I am getting:
Promise { <pending> }
I call the module like this:
var x = require("./index");
console.log(x.extractWord('docx'));
How can I obtain the result?
Thanks
CodePudding user response:
Any async
function returns a promise: you need to await
your async
function, something like this:
Give your module:
exports.extractData = async function(path) {
var mammoth = require("mammoth");
const aux = await mammoth.convertToHtml({path: path}, options);
return aux.value;
}
}
You can then say something like this:
const {extractData} = require('whatever-my-module-name-is');
async function main() {
const extractedData = await extractData();
process( extractedData ) ;
}
main()
.then( () => process.exit(0) )
.catch( err => {
console.error(err);
process.exit(1);
});
CodePudding user response:
You don't need .then when you are using async/await. async/await is just a neat replacement for promises, you shouldn't use them together
exports.extractData = async function(path) {
var mammoth = require("mammoth");
return await mammoth.convertToHtml({path: path}, options);
}