Home > Enterprise >  How to get return value of a Promise<Array[]> from an Async-Await Function?
How to get return value of a Promise<Array[]> from an Async-Await Function?

Time:05-01

Im trying to get the return value of an async-await function but im not getting the value i need.

const filterStuff = async (filters) => {
   //some code here
   await client<StuffPagination>(endpoint,body)
   .then((stuffresult)=>{
      const {stuff,page} = stuffresult;
      let fiteredStuff as Stuff[] = stuff;
      console.log(filteredStuff);
      return filteredStuff;
   })
   .catch(()=>{
      //do something
   })
   .finally(()=>{
      //do something
   });
};

How do i get the actual return value Stuff[] of the async-await function outside of the function? I have tried using .then to get the data but log for the data is always undefined while the console.log(filteredStuff) that im returning has a value. Is there something im missing?

  useEffect(() => {
    filterStuff(BaseFilters).then((data) => {
      console.log(data);
    });
  }, []);

CodePudding user response:

You are not returning at required place. Please see below updated code which await for the response.

const filterStuff = async (filters) => {
   try {
      //some code here
      const stuffresult = await client<StuffPagination>(endpoint,body);
      const {stuff,page} = stuffresult;
      let fiteredStuff as Stuff[] = stuff;
      console.log(filteredStuff);
      return filteredStuff;
   }
   catch {
      //do something
   }
   finally {
      //do something
   }
};

CodePudding user response:

you are missing a return statement in you filterStuff function

const filterStuff = async (filters) => {
   //some code here
   return client<StuffPagination>(endpoint,body)
   .then((stuffresult)=>{
      const {stuff,page} = stuffresult;
      let fiteredStuff as Stuff[] = stuff;
      console.log(filteredStuff);
      return filteredStuff;
   })
   .catch(()=>{
      //do something
   })
   .finally(()=>{
      //do something
   });
};

  • Related