0

What I want to do :

  1. I send the GET request through axios
  2. I open a local Json file with fs.readfile
  3. I process the data and return it
  4. I want to display the data when it return with res.json

what actually happened

  1. I send the GET request through axios
  2. I open a local Json file with fs.readfile
  3. They return the data before fs.readfile finished so it's undefined or blank

This one I put on the frontend and the controller

//frontend 
    const fetchRewards = async()=>{
                    let link ="/api/reward";
                    const {data} = await axios.get(link);
                    console.log(data); **// this one logging undefined**
                }

// on controller
     async getRewardsById(req,res,next) {
                try {
                    const result = await rewardService.getReward();
                    res.json(result);
                } catch (error) {
                    next(error);
                }
            },

This is my service

const getReward = async () => {
 
  fs.readFile("test.json", (err, inputData) => {
    return {"name":"John", "age":30, "car":null};
 }

  console.log("done");
}
Gregory
  • 45
  • 5
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Quentin Mar 14 '22 at 08:36
  • Hey, thank you for the reply, unfortunately I'm a bit confused. because if I remove the fs.readfile and returning straight JSON the application function normaly like I want to. – Gregory Mar 14 '22 at 09:28
  • `getReward` doesn't have a `return` statement. It returns `undefined`. The arrow function you pass to `readFile` does have a return statement. It doesn't do anything because `readFile` doesn't care what the callback function returns. See the duplicate for how you deal with using data from asynchronous callback functions. – Quentin Mar 14 '22 at 09:36

1 Answers1

-1

Seems to me like you are not returning anything from your service? Try returning the fs.readFile.

RobbeB
  • 1
  • Hi, I did return it if you closely, or like you said do I need to store that somewhere before returning? – Gregory Mar 14 '22 at 09:21
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 14 '22 at 09:32
  • `fs.readFile` doesn't return anything useful. – Quentin Mar 14 '22 at 09:36