gpt4 book ai didi

javascript - 在另一个方法中等待方法结束

转载 作者:行者123 更新时间:2023-12-03 22:32:33 24 4
gpt4 key购买 nike

我正在尝试构建一个删除目录中未使用文件的函数。我在这种方法中使用 Sequelize ORM 来获取配方。
这是我的代码

exports.deleteImagesNotUsed = (req, res) => {
// Method who send me the result at the end
const callBack = (listFiles, counter, counterfilesDeleted) => {
if (listFiles.length === counter) {
switch (counterfilesDeleted) {
case 0:
res.send({message: "No file deleted."});
break;

case 1:
res.send({message: "One file deleted."});
break;

default:
res.send({message: `${counterfilesDeleted} files deleted.`});
break;
}
}
};

const getFiles = (() => {
const directory = "./uploads";
let counter = 0;
let counterfilesDeleted = 0;
fs.promises.readdir(directory) // Get all files in directory
.then(files => {
files.forEach(file => {
if (file !== "no-image.jpg") {
Recipe.findOne({ // Select * from Recipe where imageFileName = file
where: { // It's method from Sequelize ORM
imageFileName: file
}
})
.then(data => {
if (data == null) {
const path = `${directory}/${file}`;
fs.unlinkSync(path); // Delete the file
counterfilesDeleted++;
}
});
}
counter++;
callBack(files, counter, counterfilesDeleted);
});
});
})();
}
我想在转到 counter++callBack(files, counter, counterfilesDeleted) 之前等待我的方法 Recipe.findOne 及其回调的结束。
谢谢你的帮助。

最佳答案

将该部分放在 then 方法中:

 const getFiles = (() => {
const directory = "./uploads";
let counter = 0;
let counterfilesDeleted = 0;
fs.promises.readdir(directory) // Get all files in directory
.then(files => {
files.forEach(file => {
if (file !== "no-image.jpg") {
Recipe.findOne({ // Select * from Recipe where imageFileName = file
where: { // It's method from Sequelize ORM
imageFileName: file
}
})
.then(data => {
if (data == null) {
const path = `${directory}/${file}`;
fs.unlinkSync(path); // Delete the file
counterfilesDeleted++;
}
})
.then(() => {
counter++;
callBack(files, counter, counterfilesDeleted);
});
}
});
});
})();

关于javascript - 在另一个方法中等待方法结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65505579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com