var directoryPath = path.join(__dirname, 'images');
var result = false;
fs.readdir(directoryPath, function (err, files) {
var local = false;
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
// Do whatever you want to do with the file
if(file == password) {
result = true;
}
});
});
return result
result
是对的,但是运行您的代码的单个线程在以下方面看到了更多]]var result = false
fs.readdir(directoryPath, function (err, files) => {...}) // thread: i'll just set this off
return result // thread: i'll return this immediately
因此,当您真正想要真实时,您会变得虚假。 [async/await
的操作方法如下const main = async (directoryPath, password) => {
let result = false
let files
try {
files = await fs.promises.readdir(directoryPath)
} catch (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(file => {
if (file == password) {
result = true
}
})
return result // now result will be true if file == password
}