我想在JS中創建對象的對象,但我認爲我有一些異步執行的問題。創建對象的對象
這裏是我的代碼:
// Extract data (episode number, characters firstname's) from .docx to JSON
var mammoth = require("mammoth")
function docx2Object (filepath) {
return mammoth.extractRawText({path: filepath})
.then(function (res) {
return res.value;
})
.then(function (res) {
let arr = {}
arr["number"] = "" + res.match(/(?!Episode #)\d+/)
arr["names"] = [...new Set(res.match(/^[^:\r\n]+(?=:)/gm))]
return arr
})
}
function files2JSON (arrayScripts) {
let arr = {}
let i = 0
arrayScripts.forEach(function(element) {
docx2Object(element).then(function (res) {
arr[i++] = res
console.log(JSON.stringify(arr, null, '\t'))
})
})
return JSON.stringify(arr, null, '\t')
}
let arrayScripts = ["doc1.docx", "doc2.docx"]
console.log(files2JSON(arrayScripts))
這裏是輸出:
{}
{
"0": {
"number": "10600",
"names": [
"Hilary",
"Jean-Claude",
"Devon",
"Jean Claude",
"Cane",
"Lily",
"Jack",
"Phyllis",
"Victor",
"Nikki",
"Neil",
"Paul",
"Dr. Barrett",
"Christine",
"Kelly"
]
}
}
{
"0": {
"number": "10600",
"names": [
"Hilary",
"Jean-Claude",
"Devon",
"Jean Claude",
"Cane",
"Lily",
"Jack",
"Phyllis",
"Victor",
"Nikki",
"Neil",
"Paul",
"Dr. Barrett",
"Christine",
"Kelly"
]
},
"1": {
"number": "10601",
"names": [
"Hilary",
"Devon",
"Jean+Claude",
"Jean + Claude",
"Jean/Claude",
"Jean/Claude",
"Cane",
"Lily",
"Jack",
"Phyllis",
"Victor",
"Nikki",
"Neil",
"Paul",
"Dr. Barrett",
"Christine",
"Kelly"
]
}
}
我的數組是空的,我的索引不match.Can誰能幫助?
你試過調試它,把一堆控制檯日誌放到你的函數中。並查看哪些執行,哪些不執行和您的對象發生了什麼。並告訴我,如果我錯了,但你不能有一個以上的回報,因爲第一個將取消一切波紋 – noitse