0

I'm trying to create a module in node to return a json from API using axios request. But when i try to return the response out of the function getJson(), nothing is returned to me.

const axios = require('axios');
const authentication = require('./authentication');


const url = `https://api.codenation.dev/v1/challenge/dev-ps/generate-data?token=${authentication.token}`;

const getJson = async () => {
  const response = await axios.get(url);
  // Here i can see the json normally
  console.log(response.data)
  return response.data
}

const response = getJson()
// but here nothing is shows to me in console.
console.log(response)

return of console

Azametzin
  • 5,223
  • 12
  • 28
  • 46
Igor Barbosa
  • 1
  • 1
  • 1
  • 1
    Your `getJson` function is an `async` function, which means that it returns a Promise instance. You have to wait for the promise in another `async` function with `await` or else add a `.then()` callback. – Pointy Mar 26 '20 at 17:47
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Mar 26 '20 at 17:53

2 Answers2

2

getJson() is actually returning a promise instance. You will just need to await on that like:

(async () => {
  const response = await getJson()
  console.log(response)
})();
palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

this is because const response = getJson() is executing it's code before getJson runs because it's async and the response is not arriving at that instance when it's executed.

# This code runs and executes some point in future when response arrives
const getJson = async ()=>{
  const response = await axios.get(url);
  //Here i can see the json normally
  console.log(response.data)
  return response.data
}

# This code runs and executes immediately which doesn't have response yet
const response = getJson()
  • I got it Thomas! thanks. In this case, do i need to do another async function wrapping the const to force wait the return from getJson()? – Igor Barbosa Mar 26 '20 at 18:16
  • Yes, you will another async function for it or you can use IIFE - immediately invoked function expression like I have shared. – palaѕн Mar 26 '20 at 19:07