Javascript is async in nature. So whatever modification you do inside .then
the function will only reflect inside the same scope.
So, whatever you want to do with the agent's value that you are receiving from API call should be done inside the then
function only.
let agents = [];
axios(config).then(function(response) {
agents = response.data;
console.log("agents", agents);
const mapAgents = agents.map(a => a.someProperty);
console.log(mapAgents);
// end of scope for the agent's value, it won't be accessible outside.
});
console.log(agents); // outputs []
// value of agent's won't be accessible here due to async nature. This line will get executed first and then.
async-await
If you wish to perform some action in a synchronous fashion. You can achieve it using async-await
, it makes the inside of the function synchronous while keeping the execution of function as asynchronous.
const getAgents = async function() {
let agents = []
const res = await axios(config) // thread will wait till the api call is completed
agents = res.data
// perform your action here
}
getAgents(); // this will now become asynchronous
You can learn more about the Javascript async nature, here.