首页 > 解决方案 > 如何在下面的 readFile 代码中使用 Promise.all?

问题描述

在下面的代码中,我正在读取一些文件并获取它们的文件名和文本。之后,我将数据存储在选项变量中以生成 epub 文件:

const Epub = require("epub-gen")
const folder = './files/'
const fs = require('fs')
let content = []

fs.readdir(folder, (err, files) => {
  files.forEach(filename => {
    const title = filename.split('.').slice(0, -1).join('.')
    const data = fs.readFileSync(`${folder}${filename}`).toString('utf-8')
    content.push({ title, data })
  })
})

const option = {
  title: "Alice's Adventures in Wonderland", // *Required, title of the book.
  content
}

new Epub(option, "./text.epub")

问题是,new Epub在读取文件之前运行,在content准备好之前。我认为Promise.all这里是合适的人选。我检查了Mozilla文档。但它显示了各种承诺作为例子,但我没有。所以,我不太确定如何在Promise.all这里使用。

有什么建议吗?

标签: javascriptpromisees6-promise

解决方案


你的问题是 with readdir,它是异步的new Epub,所以就像你已经想通的那样,在它的参数之前被调用。callback

在, after的参数内切换使用readdirSync或移动。const option ... new Epub...callbackreaddirfiles.forEach


推荐阅读