so this is my code:
watcher.on('add', async (filePath) => {
const relativePath = path.relative(directoryToWatch, filePath);
const folder = path.dirname(relativePath).split(path.sep)[0];
console.log(folder);
console.log("1");
try {
let folderExist = folderJobsList.find((item) => item.folder === folder);
console.log(folderExist);
console.log("2");
if (!folderExist) {
console.log("3");
// Use a Promise to wait for the job creation
job = await new Promise(async (resolve, reject) => {
try {
const createdJob = await JobModel.create({
folder,
status: 'pending',
});
console.log("4");
folderJobsList.push({ folder });
console.log("5");
console.log("*********");
console.log(JSON.stringify(folderJobsList));
console.log("*********");
console.log(JSON.stringify(createdJob));
console.log("---------");
resolve(createdJob);
} catch (error) {
reject(error);
}
});
console.log("6");
const file = await FileModel.create({
filename: filePath,
relativePath: filePath,
status: 'pending',
jobId: job.id,
});
console.log('File added to the database:', file);
console.log("7");
}
} catch (error) {
console.error('Error creating File:', error);
}
})
so i'm adding a folder with multiple other folders and files. what the code is doing is when it first begin to create the first job (which is the main folder, just adding it to the DB with its path), it actually logs 3 and re do the whole process again and it dosent wait until the first job is actually created.
I just want it to wait not to jump.
Seems to be related to the way the
try/catchblock is structured inside the callback. The asyncJobModel.createmight be causing the subsequent code to execute before the job is actually created.See this one, creating a promise and awaiting the job inside it: