0

I am attempting to use the Mammoth Node.js package to convert a file from Docx to HTML. The Mammoth Readme suggests the following format for converting the file:

var mammoth = require("mammoth");

mammoth.convertToHtml({path: "path/to/document.docx"})
    .then(function(result){
        var html = result.value; // The generated HTML
        var messages = result.messages; // Any messages, such as warnings during conversion
    })
    .done();

I have placed this template code within a convertDoc function and I am attempting to use the value of html elsewhere in the code after calling the convertDoc function.

Placing a return html statement anywhere within the convertDoc function will not allow me to use the stored html, however I can output the correct html contents to console. I need advice on how to return/make use of the html variable from outside the promise, thanks.

  • What research has been accomplished to this point? What is your level of experience? This has been asked a time or two before: https://stackoverflow.com/questions/37533929/how-to-return-data-from-promise – DtechNet Nov 29 '18 at 14:48
  • You don't. You call `.then` on the promise. You cannot reliably access the data outside of a `.then` handler. – Jared Smith Nov 29 '18 at 14:59

1 Answers1

2

When functions return promises, you get the promise from the function, and setup some sort of effect for when the promise resolves. You do that by passing a function to the promise using then. This is quite a crude explanation and I'd recommend you read the docs on promises.

Here's how the code may look:

const mammothMock = {
  convertToHtml: path => Promise.resolve({value: `<p>Test Html from ${path}</p>`})
}

const mammoth = mammothMock;

const convertFileToHtml = youCouldTakeAPathHere => mammoth
  .convertToHtml(youCouldTakeAPathHere)
  .then(function(result){

      return result.value;
  })

convertFileToHtml('some/test/path.docx')
  .then(result => document.body.append(result))
OliverRadini
  • 6,238
  • 1
  • 21
  • 46