最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin21浏览0评论

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

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

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

评论列表(0)

  1. 暂无评论