skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

     var x = await getAvgPrice();
     console.log(x);
    
    Login or Signup to reply.
  3. 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.

    const axios = require("axios");
    
    // Approach 1
    function getAvgPrice() {
        var data = []; // or whatever we would have to declare for a json object
        return 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;
            });
    }
    
    // Approach 2
    // async function getAvgPrice() {
    //     var data = []; // or whatever we would have to declare for a json object
    //     const res = await axios.get("https://api.com/example.json")
    //     data.push(res);
    //     return data;
    // }
    
    getAvgPrice().then((res) => {
        console.log(res); // <-- (Fixed - Output: Promise { <pending> })
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search