returns 承诺的循环库 - 同步
Looping library which returns a promise - sync
我对这段代码摸不着头脑:我读取文件夹内容,通过 mammoth convert 循环接收文件(returns 一个承诺),然后我创建了一个我想要呈现的对象。
我尝试过异步和承诺,但从未能够使其同步。能请教一下吗?
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收集结果的概念^^;.
我认为记住 Promise.all()
可以收集 Promise 的结果是一个很好的起点。
请尝试以下。
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});
})
});
我对这段代码摸不着头脑:我读取文件夹内容,通过 mammoth convert 循环接收文件(returns 一个承诺),然后我创建了一个我想要呈现的对象。 我尝试过异步和承诺,但从未能够使其同步。能请教一下吗?
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收集结果的概念^^;.
我认为记住 Promise.all()
可以收集 Promise 的结果是一个很好的起点。
请尝试以下。
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});
})
});