Hello friends I have a problem I have a promise executing but it does not finish when the console.log is already printing, I understand that async await should be used but I cannot understand how I can implement it in my code
function consumoApi() {
for (let i = 0; i < 5; i++) {
axios.get(`https://dsadsadsadas.dsa/dsa/2019-12-0${i + 1}`).then((response) => {
response.data.forEach((element) => {
data.push(element);
});
});
}
console.log(data)
}
Remember that you can always check the Javascript documentation . Even in the Axios documentation there is an example of how to use async/await with
get
.Basically, to implement async/await, you must declare it
async
in your function, in this way, what will be returned will be a Promise .This way, you can use
await
inside that function, that will make the execution of the code wait until the data coming from the API is available. It should be noted that when usingawait
, the result would be returned from the function, but in case of error you must use try...catch .So your code would look like this (it takes a while to get the results):
A better implementation could be like this: