首页 > 解决方案 > 错误:当函数已经在异步函数中时,等待仅在异步函数中有效

问题描述

目标:从我的目录中获取文件列表;获取每个文件的 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);
    })
});

标签: node.jsasynchronoussha256

解决方案


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

在这个新的实现中:

  1. 用于const fsp = require('fs').promises获取fs模块的 Promise 接口。
  2. 使用await fsp.readdir()Promise 读取文件
  3. 使用for/of循环,这样我们就可以正确地使用await.
  4. 调用该函数并监视完成和错误。

推荐阅读