【问题标题】:Error: await is only valid in async function when function is already within an async function错误:当函数已经在异步函数中时,等待仅在异步函数中有效
【发布时间】:2020-03-27 08:38:27
【问题描述】:

目标:从我的目录中获取文件列表;获取每个文件的 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() 回调中。此外,forEach() 不支持承诺,因此它将并行运行您的所有迭代。如果您将.forEach() 切换为普通的for (let i of getAllFiles) 循环,则上述两个问题都将得到解决。
  • 另外,getFiles() 实际上并没有返回任何东西,所以const getAllFiles = getFiles() 将不起作用。同样,您需要了解.forEach() 接受单独的回调并且从它返回不会对父函数做任何事情。
  • 您不能将 forEach 与 async-await 一起使用(或者至少,它不会按照您希望的方式工作)。请改用普通的 for 循环。

标签: node.js asynchronous sha256


【解决方案1】:

您的await 不在async 函数内,因为它在未声明async.forEach() 回调内。

您确实需要重新考虑如何处理此问题,因为 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() 通过promises 读取文件
  3. 使用for/of 循环,以便我们可以使用await 正确排序异步操作。
  4. 调用函数并监控完成和错误。

【讨论】:

  • 感谢您指出我的代码中的问题!你的解决方案奏效了。
猜你喜欢
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2020-10-03
  • 2021-01-11
相关资源
最近更新 更多