async/await loop array.push issue

1.6k Views Asked by At

I'm currently working on something where I need to get async data and push it to an array. Please see below.

const getStudent = async (id: string) => {
  const student = await fetchSomeData(id); 
  const markedEssayArray: string[] = [];
  
  for await(const essayName of student.essay) {
    const markedEssay = await fetchMarkedEssay(essayName);

    markedEssayArray.push(markedEssay)
  };
 
  student.essay = markedEssayArray;

  return student;
};

so basically, I fetch a student, and update the student.essay array with the marked versions. However when I test the code, the student.essay array returns an empty array [].

Could anyone kindly advise where I went wrong?

1

There are 1 best solutions below

0
On

You can try like this :

const getStudent = async (id: string) => {
  const student = await fetchSomeData(id); 
  let markedEssayArray: string[] = [];
  const essayArr = student.essay;

  essayArr.forEach((singleEssay) => {
    let markedEssay = await fetchMarkedEssay(essayName);

    markedEssayArray.push(markedEssay)
  }
   
  student.essay = [...markedEssayArray];

  return student;
};