我正在尝试使用Mammoth包将文件从Docx转换为Node.js。Mammoth自述文件建议使用以下格式转换文件:
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();我将此模板代码放在一个convertDoc函数中,并在调用convertDoc函数后尝试在代码中的其他地方使用html的值。
将return html语句放在convertDoc函数中的任何位置都不允许我使用存储的html,但是我可以将正确的html内容输出到控制台。我需要关于如何从promise外部返回/使用html变量的建议,谢谢。
发布于 2018-11-29 22:55:47
当函数返回promise时,您将从函数中获取promise,并在promise解析时设置某种效果。您可以通过使用then将函数传递给promise来完成此操作。这是一个相当粗糙的解释,我推荐你使用read the docs on promises.
下面是代码可能的样子:
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))
https://stackoverflow.com/questions/53541580
复制相似问题