0

I'm having a problem with my code. I need to check if there's an item in cutlist array with a material_id that does not exist in materials database, but the code inside the forEach is executing after the function is finished.

const errors: string[] = [];

await orderData.cutlist.forEach(async cutlist => {
  const doesMaterialExist = await this.materialsRepository.findMaterialById(
    cutlist.material_id,
  );

  if (!doesMaterialExist) {
    errors.push('Material does not exist');
  }

 console.log('1')
});

console.log('2')

if (errors.length > 0) {
  throw new AppError('There is a invalid material in cutlists', 404);
}

My console after executing this code is 2 -> 1. It is checking the errors.length before the ForEach loop

1 Answers1

0

You can't use await before forEach loop. There's ways to do that but in your case, that's not necessary.

You can convert forEach to a for loop and your problem will be solved.

const errors: string[] = [];

for(var cutlist in orderData.cutlist){
  const doesMaterialExist = await this.materialsRepository.findMaterialById(
    cutlist.material_id,
  );

  if (!doesMaterialExist) {
    errors.push('Material does not exist');
  }

 console.log('1')
};

console.log('2')

if (errors.length > 0) {
  throw new AppError('There is a invalid material in cutlists', 404);
}
Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27