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

回眸只為那壹抹淺笑 提交于 2021-02-11 14:53:16

问题


Goal: Get a list of files from my directory; get the SHA256 for each of those files

Error: await is only valid in async function

I'm not sure why that is the case since my function is already wrapped inside an async function.. any help is appreciated!

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

回答1:


Your await isn't inside an async function because it's inside the .forEach() callback which is not declared async.

You really need to rethink how you approach this because getFiles() isn't even returning anything. Keep in mind that returning from a callback just returns from that callback, not from the parent function.

Here's what I would suggest:

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

In this new implementation:

  1. Use const fsp = require('fs').promises to get the promises interface for the fs module.
  2. Use await fsp.readdir() to read the files using promises
  3. Use a for/of loop so we can properly sequence our asynchronous operations with await.
  4. Call the function and monitor both completion and error.


来源:https://stackoverflow.com/questions/60878086/error-await-is-only-valid-in-async-function-when-function-is-already-within-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!