I'm learning Promises and I tried to fetch some data inside an async function.
Here's the snippet -
import "./styles.css";
import axios from "axios";
let jsonPlaceholder = axios.create({
baseURL : "https://jsonplaceholder.typicode.com/"
})
let fetchData = async () => {
console.log("INSIDE FETCH DATA FUNCTION")
let response = await jsonPlaceholder.get('/users');
return response.data;
}
let runSetTimeoutTenTimes = () => {
for(let i=0; i<10; i++) {
setTimeout(async () => {
let data = await fetchData();
console.log("HERE IS THE USER DATA....",data);
})
}
}
runSetTimeoutTenTimes();
I was expecting the output similar to the below format in console:
INSIDE FETCH DATA FUNCTION
HERE'S THE DATA....
(10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
INSIDE FETCH DATA FUNCTION
HERE'S THE DATA....
(10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
.
.
.
However I am getting data in the below format:
It looks like fetchData
is run 10 times and then fetched data are logged one by one.
What am I missing here ?
EDIT:
If I replace the fetchData
and runSetTimeoutTenTimes
with the below functions I am getting the desired result:
let fetchData_1 = async () => {
console.log("INSIDE FETCH DATA FUNCTION")
return;
}
let runSetTimeoutTenTimes = () => {
for(let i=0; i<10; i++) {
setTimeout(async () => {
await fetchData();
console.log("HERE IS THE USER DATA....");
})
}
}