Reputation: 2045
I have code like follow. What i intend to do is:
1) For loop and call api with sequence.
2) The next for loop iteration only executed after the promise resolve, with a 1 second delay.
I am doing this way but console.log prints nothing. What is the correct way to approach it?
const axios = require('axios');
function getData(i){
return axios.get(`http://www.api.com/${i}`);
}
for (let i = 0; i < 10000000; i++) {
setTimeout(() => {
getData(i)
.then((res) => {
console.log(`successs ${i}`);
})
.catch((err) => {
console.log(`fail ${i}`);
})
}, 1000)
}
Upvotes: 0
Views: 1113
Reputation: 1849
Your code basically runs 10000000 api requests simultaneously after 1 second delay. You need to chain API calls so they are run after another:
const axios = require('axios');
function getData(i){
return axios.get(`http://www.api.com/${i}`);
}
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function dataLoop() {
const getOne = (i: number) => {
if (i < 10000000) {
getData(i)
.then((res) => {
console.log(`successs ${i}`);
})
.catch((err) => {
console.log(`fail ${i}`);
})
.then(wait(1000))
.then(() => getOne(i + 1))
}
}
getOne(0);
}
dataLoop();
I suggest to try using async/await if possible in your situation, it greatly simplifies things.
for (let i = 0; i < 10000000; i++) {
try {
const res = await getData(i);
console.log(`successs ${i}`);
} catch (e) {
console.log(`fail ${i}`);
}
await wait(1000);
}
Upvotes: 2