【问题标题】:How do I retrieve data from a Promise [duplicate]如何从 Promise 中检索数据 [重复]
【发布时间】:2019-05-01 16:01:06
【问题描述】:

我正在尝试使用 Mammoth Node.js 包将文件从 Docx 转换为 HTML。 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 的值。

convertDoc 函数中的任何位置放置return html 语句将不允许我使用存储的html,但是我可以将正确的html 内容输出到控制台。我需要关于如何从承诺之外返回/使用 html 变量的建议,谢谢。

【问题讨论】:

  • 目前已经完成了哪些研究?你的经验水平如何?这已经被问过一两次了:stackoverflow.com/questions/37533929/…
  • 你没有。你打电话给.then 承诺。您无法可靠地访问 .then 处理程序之外的数据。

标签: javascript node.js promise mammoth


【解决方案1】:

当函数返回 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))

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多