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)
getJson()
is actually returning a promise instance. You will just need to await
on that like:
(async () => {
const response = await getJson()
console.log(response)
})();
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.