函数中已有功能时,等待才在异步函数中有效"/>
错误:仅当异步函数中已有功能时,等待才在异步函数中有效
目标:从我的目录中获取文件列表;为每个文件获取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);
}
});
更多推荐
错误:仅当异步函数中已有功能时,等待才在异步函数中有效
发布评论