错误:仅当异步函数中已有功能时,等待才在异步函数中有效

编程入门 行业动态 更新时间:2024-10-28 20:21:05

错误:仅当异步<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数中已有功能时,等待才在异步函数中有效"/>

错误:仅当异步函数中已有功能时,等待才在异步函数中有效

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

您传递给forEach的回调也必须为async,以使等待有效:

(async () => {
    const getAllFiles = getFiles()
    getAllFiles.forEach( async (i) => {
        const hash = await hasha.fromFile(i, {algorithm: 'sha256'});
        return console.log(hash);
    })
});

但是,这将导致奇怪的行为,因为您的外部函数将在所有散列发生之前输出。这是由于forEach不太关心async回调。

要解决此问题,请用forEach块替换for

(async () => {
    const getAllFiles = getFiles();

    for(let i = 0; i < getAllFiles.length; i++) {
        const hash = await hasha.fromFile(i, {algorithm: 'sha256'});
        return console.log(hash);
    }
});

更多推荐

错误:仅当异步函数中已有功能时,等待才在异步函数中有效

本文发布于:2024-05-07 03:10:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754170.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   已有   错误   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!