I’m trying to send a request to an api using axios and store the json response in a variable. When I output the response to the console, it shows it, but when setting a variable equal to it and returning said variable, I only get Promise { } as an output.
const { default: axios } = require("axios");
async function getAvgPrice() {
var data = []; // or whatever we would have to declare for a json object
await axios.get("https://api.com/example.json")
.then(function(res) {
console.log(res); // <-- This outputs the correct response to console
data.push(res); // <-- This just doesn't do anything
});
return data;
}
var x = getAvgPrice();
console.log(x); // <-- (Output: Promise { <pending> })
I tried to send a request to an api and store the response as json and am only able to return a promise.
3
Answers
You need to await the getAvgPrice(); since it’s an async fuction.
So
const x = await getAvgPrice();
will work and get you the actual data.When you call an async function, it returns a Promise, which is why you see
Promise { <pending> }
.You must using await when calling the async function:
So axios calls are asynchronous, it doesn’t wait for the data to be fetched before continuing. It returns a Promise object immediately, that’s why you are seeing
Promise { <pending> }
.returned statement you have added is not a part of callback
.then
which is executed after the asynchronous task of axios call is completed.You should have returned the data in
.then
callback.Try one of following approaches both will work.