I am trying to create an array with map, and for each iteration I need to get information with get axios, but the new array variable at the end of the map brings me the elements as undefined.
let nuevo_arreglo = main_res.results.map( item => {
axios.get(url).then(res => {
return res
})
});
Is there a way to make it save the array correctly, I'm new to javascript.
ISSUE
As I say in my comment , your problem (and it always is) is one of asynchrony.
If we do a mental exercise of what is happening with your code, you have a list (array) of items, and for each of them you make a request type
get
usingaxios
, which is a libraryhttp
based on Promises . This means that the result of that request will be available at an uncertain future time, making the assignment of the method resultmap
to your variablenuevo_arreglo
not actually have the data returned from that Promise(s). Even if they returned immediately, their content would be an Object of type Promise and not the processed result of the Promise.SOLUTION
One possible solution is to use the method
Promise.all
to process the new array once all Promises from the original array have been processed. However, since itPromise.all
returns a Promise, the correct way to continue working with the result of the Promise is inside the methodthen()
of said Promise.We can see a working example, using the randomuser.me API , to process a list of requests:
Another way to solve the problem is to use
async / await
and a loopfor ... of
. But for this to work, your code must be executed in an environment typeasync
(note that I've wrapped the anonymous function in parentheses and put double parentheses at the end to indicate its execution:(func_anonima)()
), for example:I hope this helps you solve the problem.