-1

i want to start all lines after async foreach finished because element variable override before foreach finished, should interpreter stops before foreach finished

Object.keys(parsed).forEach(async (key) => {
  let { cleanInput, errors } = await validateFullUserInput(
    parsed[key],
    branch,
    language
  );
  parsed[key] = cleanInput;
  // console.log(parsed[key]);
  if (errors.length > 0) {
    arr.push.apply(arr, errors);
  }
  console.log(parsed);
});
// console.log(parsed);
element = parsed;

if (arr.length > 0) {
  rejected.push(element);
} else {
  if (
    Object.keys(element.student).length > 0 ||
    Object.keys(element.firstGuardian).length > 0
  ) {
    success.push(element);
  }
}

1 Answers1

-1

You can use the Promise.all() method to wait for all the asynchronous operations inside the forEach() loop to complete before executing the next lines of code. Here's how you can modify your code to achieve this:

async function validateData(parsed, branch, language) {
  let arr = [];
  let success = [];
  let rejected = [];

  await Promise.all(
    Object.keys(parsed).map(async (key) => {
      let { cleanInput, errors } = await validateFullUserInput(
        parsed[key],
        branch,
        language
      );
      parsed[key] = cleanInput;
      // console.log(parsed[key]);
      if (errors.length > 0) {
        arr.push.apply(arr, errors);
      }
      console.log(parsed);
    })
  );

  console.log(parsed);
  if (arr.length > 0) {
    rejected.push(parsed);
  } else {
    if (
      Object.keys(parsed.student).length > 0 ||
      Object.keys(parsed.firstGuardian).length > 0
    ) {
      success.push(parsed);
    }
  }

  return { success, rejected };
}
user23012
  • 219
  • 2
  • 16
  • 1
    In order to successfully use promise.all on an array of promises, that array of promises should exist. Currently the map function returns nothing, so I expect promise.all is trying to handle an array of `undefined`. – James Mar 30 '23 at 17:31