node.js - 错误:当函数已经在异步函数中时,等待仅在异步函数中有效
问题描述
目标:从我的目录中获取文件列表;获取每个文件的 SHA256
错误:await is only valid in async function
我不确定为什么会这样,因为我的函数已经包含在异步函数中..任何帮助表示赞赏!
const hasha = require('hasha');
const getFiles = () => {
fs.readdir('PATH_TO_FILE', (err, files) => {
files.forEach(i => {
return i;
});
});
}
(async () => {
const getAllFiles = getFiles()
getAllFiles.forEach( i => {
const hash = await hasha.fromFile(i, {algorithm: 'sha256'});
return console.log(hash);
})
});
解决方案
您await
不在async
函数内,因为它在.forEach()
未声明的回调内async
。
你真的需要重新考虑如何处理这个问题,因为getFiles()
它甚至没有返回任何东西。请记住,从回调返回只是从该回调返回,而不是从父函数返回。
这是我的建议:
const fsp = require('fs').promises;
const hasha = require('hasha');
async function getAllFiles() {
let files = await fsp.readdir('PATH_TO_FILE');
for (let file of files) {
const hash = await hasha.fromFile(i, {algorithm: 'sha256'});
console.log(hash);
}
}
getAllFiles().then(() => {
console.log("all done");
}).catch(err => {
console.log(err);
});
在这个新的实现中:
- 用于
const fsp = require('fs').promises
获取fs
模块的 Promise 接口。 - 使用
await fsp.readdir()
Promise 读取文件 - 使用
for/of
循环,这样我们就可以正确地使用await
. - 调用该函数并监视完成和错误。
推荐阅读
- python - Python --version Windows 只返回单词 Python
- android - 我创建了一个对象列表,listview 不会显示它
- javascript - 如何检查某个文件系统路径下的某个或多个文件是否存在?
- ios - 禁用自动更正类型不适用于 UITextfield
- c++ - 在 C++ 中通过引用传递整个数组的不同方法
- spring-batch - Spring Batch:显示加载失败的错误行号
- python - Python:使用 OpenCV 无法识别 Panasonic 网络流
- android - 使用默认应用程序 nativescript 7 打开文件
- python - 将图像传递给 python FastAPI api 端点
- api - 根据文档的自定义字段使用 Graph 查询 SharePoint