Home > other >  Async Javascript function is returning undefined in NodeJS
Async Javascript function is returning undefined in NodeJS

Time:11-09

I am trying to call a function which gets data from an API and after comaprison of received data with input it should return 0 or 1 which i may include in my code but the function is returning undefined. Can;t seem to get my head in the right place.


async function cloudVerify(y, x) {
  const url = `https://**myAPI**.execute-api.us-west-2.amazonaws.com/items/${y}`;
  console.log(url);
  await axios
    .get(url)
    .then((res) => {
      const headerDate =
        res.headers && res.headers.date ? res.headers.date : "no response date";
      console.log("Status Code:", res.status);
      console.log("Date in Response header:", headerDate);

      const receivedData = res.data;
      const receivedItem = receivedData.Item;
      // console.log(receivedItem);
      console.log(
        `Got user with id: ${receivedItem.id}, hash: ${receivedItem.hash}`
      );
      console.log(`received item hash is ${receivedItem.hash}`);
      console.log(`meta is : ${x}, hash: ${receivedItem.hash}`);
      return 1;
    })
    .catch((err) => {
      console.log("Error: ", err.message);
    });
}

output in node js I am returning 1 but instead it gives me undefined.

CodePudding user response:

When you return 1 inside the "then" method you will not return it from the cloudVerify function. You need to type return before "await axios" as well.

CodePudding user response:

I think it's a scoping issue. the "return 1" is returned by your call to axios within cloudVerify, it's not the return value of that function.

Also, you might be mixing async/await with .then() - you might be able to drop the async/await and simply return the call to axios. kind of like this:

callingAxios = () => {
  axios.get().then()
  return 1
}

cloudVerify = (url) => {
  return callingAxios(url)
}
  • Related