Awaiting code until filter is finished - Nextjs/Javascript

Viewed 27

I am looking on how to make my code after my filter function await the results of my filter function to complete before running. However I am not sure how to do this.

My filter function takes in another function (useLocalCompare) which causes the execution of my filter function to be a little longer than normal, which then leads to my next piece of code (that depends on the results of my filter function) executing before my filter function is complete.....which leads to undefined.

Is there anything similar to a callback I can use to force my subsequent piece of code to wait till the filter is finished?

Relevant code is written below.

if (flatarrayofvalues !== null && genre !== null) {
      const filtteredarray = await flatarrayofvalues.filter(
        (placeholder) => {
          if (useLocalCompare(genre, placeholder.name) == true) {
            console.log("HURAY!!!!", placeholder.id, placeholder.name);
            placeholder.name == placeholder.name;
          }
        }
      );
      console.log("MY FILTERED ARRAY IS", filtteredarray);
      console.log("The ID FOR MY MY FILERED ARRAY IS two ID", filtteredarray[0]?.id);
   return filtteredarray[0].id;
}

} }

For those curious, useLocalCompare basically checks to see if the genre parameter pulled down from the URL is the same as a name parameter from the array I am filtering. Reason I have this is due to people having different case sensitivity when putting in URLS. EX: it will pull down "HORrOR" and match it to the object name in the array I am filtering called "horror". I then extract the ID from that object.

1 Answers

you have to return the conditional from filter as it is "explicit return"

const filtteredarray = await flatarrayofvalues.filter(
    (placeholder) => {
      if (useLocalCompare(genre, placeholder.name) == true) {
        console.log("HURAY!!!!", placeholder.id, placeholder.name);
        return placeholder.name == placeholder.name;  // here
        // why not just return true ?? instead of above line
      }return false
    }
  );

Also I'm not sure this makes sense

placeholder.name == placeholder.name; you mean just return true; ?

Related