Error: await is only valid in async function when function is already within an async function

Error: await is only valid in async function when function is already within an async function

目标:从我的目录中获取文件列表;获取每个文件的 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() 回调中,但未声明 [​​=12=].

您确实需要重新考虑如何处理此问题,因为 getFiles() 甚至没有返回任何内容。请记住,从回调中返回只是 returns 来自该回调,而不是来自父函数。

以下是我的建议:

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);
});

在这个新的实现中:

  1. 使用 const fsp = require('fs').promises 获取 fs 模块的承诺接口。
  2. 使用 await fsp.readdir() 使用 promises 读取文件
  3. 使用 for/of 循环,以便我们可以使用 await 对异步操作进行正确排序。
  4. 调用函数并监视完成和错误。