javascript - 如何在下面的 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
这里使用。
有什么建议吗?
解决方案
你的问题是 with readdir
,它是异步的new Epub
,所以就像你已经想通的那样,在它的参数之前被调用。callback
在, after的参数内切换使用readdirSync
或移动。const option ... new Epub...
callback
readdir
files.forEach
推荐阅读
- c# - 当 Quartz 作业运行时出现“对象引用未设置为对象的实例”时出错
- vhdl - 如果合成器报告错误的行号,我如何找到重复的信号定义?
- ios - Swift CollectionView(致命错误:索引超出范围)
- python - python pandas到csv文件保存,不覆盖
- reactjs - 使用 ErrorBoundary 组件在同一页面上反应 JS shwo 错误
- python - Django-传递参数/过滤问题
- php - Codeigniter 重定向无法正常工作
- c# - 无法从 C# 中的 Mysql 数据库中的 WPF 数据网格中的图像获得一个以上的结果
- reactjs - 功能放置最佳实践
- r - 将字符转换为日期和数字,保持相同的格式