问题
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:
- Use
const fsp = require('fs').promises
to get the promises interface for thefs
module. - Use
await fsp.readdir()
to read the files using promises - Use a
for/of
loop so we can properly sequence our asynchronous operations withawait
. - 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