这段代码让我摸不着头脑:我读取文件夹内容,通过mammoth convert(返回一个承诺)循环接收到的文件,然后创建一个我想要呈现的对象。 我尝试过使用异步和承诺,但从未使其同步。 请你指点一下好吗?
fs.readdir('Documents', function (err, files) {
files.forEach(function (file) {
mammoth.convertToHtml({path: "Documents/"+file},options)
.then(function(result){
var html = result.value; // The generated HTML
var messages = result.messages; // Any messages, such as warnings during conversion
docContent.push({
"skillName" : file,
"skillData" : html
})
}).done()
});
});
res.render("index",{docContent:docContent});
我也很难理解收集承诺结果的概念^^;。
我认为最好从记住promise.all()
可以收集承诺结果开始。
请试试下面。
fs.readdir('Documents', function (err, files) {
// convertingJob = [Promise, Promise,...]
const convertingJob = files.map(function(file) {
// just return promise and it will make above convertingJob array
return mammoth.convertToHtml({path: "Documents/"+file},options)
.then(function(result){
var html = result.value; // The generated HTML
var messages = result.messages; // Any messages, such as warnings during conversion
// docContent.push({
// "skillName" : file,
// "skillData" : html
// })
return {
"skillName" : file,
"skillData" : html
}
})
// .done() // I'm not sure this is necessary
});
Promise.all(convertingJob) // Gather(wait) all Promise results!
.then(jobResults => { // jobResults would be array of objects returned by mammoth
res.render("index",{docContent:jobResults});
})
});