please check the below axios get request example to a random public api.
Intro
I would simply like to create a function which will execute get requests and return data, so I can store the returned data in a variable and use it in the UI I am building.
Currently the function returns Promise object and not data as expected.
I also noticed that returned promise object is printed before logged data response. This makes me think that for some reason return command doesn't await the resolution of the promise.
I can use any other library apart axios as well, but tried fetch which is giving me same results.
Furthermore, I tried executing correct code from other stackoverflow answers on this topic, but it gave me same results. Which leads me thinking my issue has something to do with my environment.
What I already tried
- I looked into all answers on query "axios request returns undefined" and similar
- I looked into all answers on query "get data from axios request" and similar
- tried executing the code from browser using react
- changing the function to synchronous, which instead of Promise object return
undefined
My env:
- System Version: macOS Monterey 12.4 (21F79)
- Kernel Version: Darwin 21.5.0
- Node@v18.7.0
- axios@0.21.4
- iterm@2
Example
The example can be executed by running node script.js
.
// filename: script.js
const axios = require("axios");
async function fetchApi() {
const getRequest = await axios.get("https://api.publicapis.org/entries")
.then((response) => {
console.log("logged response:", response.data.count);
return response.data.count;
})
};
const response = fetchApi();
console.log("returned response:", response);
// execute@bash: node script.js
// returned response: Promise { <pending> }
// logged response: 1425
My question
I would expect returned result and logged result to be the same.
Please help me troubleshoot this issue.