带有promise的函数不返回结果

时间:2017-08-30 08:59:25

标签: javascript promise

我是JS的新承诺,我不明白为什么我的函数没有返回预期的结果。

这是我的代码:

// Extract firstname actor form .docx to JSON

var mammoth = require("mammoth")
var fs = require('fs')

function pdocx (filepath) {
    
    return mammoth.extractRawText({path: filepath})
    .then(function (res) {
        return res.value;
    })
    .then(function (res) {
        let arr = {}
        arr["episode"] = [...new Set(res.match(/(?!Episode #)(\d+)/))]
        arr["names"] = [...new Set(res.match(/^[^:\r\n]+(?=:)/gm))]
        console.log(JSON.stringify(arr, null, '\t'))
        return JSON.stringify(arr, null, '\t')
    })
}

console.log(pdocx("doc.docx"))

该函数中的console.log显示了良好的结果:

{
"episode": [
    "10600"
],
"names": [
    "Hilary",
    "Jean-Claude",
    "Devon",
    "Jean Claude",
    "Cane",
    "Lily",
    "Jack",
    "Phyllis",
    "Victor",
    "Nikki",
    "Neil",
    "Paul",
    "Dr. Barrett",
    "Christine",
    "Kelly"
]

}

但我在函数外的console.log上有错误:

    Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

感谢您的帮助!

编辑:

当我这样做时它会起作用,但不确定这是做出承诺最干净的方式:

function pdocx (filepath) {
    
    return mammoth.extractRawText({path: filepath})
    .then(function (res) {
        return res.value;
    })
    .then(function (res) {
        let arr = {}
        arr["episode"] = [...new Set(res.match(/(?!Episode #)(\d+)/))]
        arr["names"] = [...new Set(res.match(/^[^:\r\n]+(?=:)/gm))]
        return JSON.stringify(arr, null, '\t')
    })
}

pdocx("doc.docx").then(function (res) {
    console.log(res)
})

0 个答案:

没有答案