0

but when i go on the that link there's json data.

import axios from "axios";
exports.handler = async function (event, context) {
  let results;
  const fetchData = async () => {
    axios.get("https://randomuser.me/api").then((res) => {
      console.log(res);
    });
    // conlog.log(results.data);
  };

  return {
    statusCode: 200,
    body: JSON.stringify(fetchData()),
  };
};

here's my code i tried to read this with python requests and it worded fine.

i even tried

import axios from "axios";
exports.handler = async function (event, context) {
  return {
    statusCode: 200,
    body: JSON.stringify(axios.get("https://randomuser.me/api")),
  };
};

but it still returns an {}. can someone please tell me what am doing wrong here.

Edit:

i at first had this:

import axios from "axios";
exports.handler = async function (event, context) {
  let results;
  const fetchData = async () => {
    results = await axios.get("https://randomuser.me/api");
    conlog.log(results.data);
    return results.data;
  };

  return {
    statusCode: 200,
    body: JSON.stringify(fetchData()),
  };
};

Edit 2:

i Have this code below as part of my app.js and it works just fine.

 const fetchData = async () => {
    const results = await axios.get("/.netlify/functions/print");
    console.log(results);
  };

  useEffect(() => {
    fetchData();
  }, []);
knvgpt
  • 17
  • 3
  • 1
    `body: JSON.stringify(fetchData())` ... ferchData returns a promise. Perhaps you should await it – Jaromanda X Jul 11 '22 at 13:10
  • Does this answer your question? [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – evolutionxbox Jul 11 '22 at 13:14

3 Answers3

1

You should add await to the fetchData async function. And remove async from the parent function

import axios from "axios";
exports.handler = function (event, context) {
  let results;
  const fetchData = async () => {
   await axios.get("https://randomuser.me/api").then((res) => {
      console.log(res);
    });
    // conlog.log(results.data);
  };

  return {
    statusCode: 200,
    body: JSON.stringify(fetchData()),
  };
};
0

You should add await to async function

-1

I think the problem should be with how i call the function cause even a basic console.log("hello") is not getting printed to the console from inside that function

knvgpt
  • 17
  • 3
  • 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 Jul 12 '22 at 20:16