Reputation: 97
I am trying to axios requests inside a for loop but the loop is being completed even before the axios. Following is my code:
let findEmail = async() => {
for (var i = 0; i < csvData.length; i++){
axios.post('https://email-finder.herokuapp.com/find', {
"first_name": "Irinaa",
"last_name": "xyz",
"domain": "xyxz.com"
}).then((response) => {
if(response.status === 500){
console.log('no email found');
}
else{
console.log(response.data);
}
}, (error) => {
console.log('no email found ', i);
});
console.log('axios request done');
}
}
I want the loop to wait until the request is complete and then go to increment the i variable. Any help would be much appreciated. Thank you
Upvotes: 1
Views: 2541
Reputation: 21
Another pattern to consider: use an array of promises and Promise.all.
For example:
let findEmail = async() => {
const promises = []
for (var i = 0; i < csvData.length; i++){
const request = axios.post('https://email-finder.herokuapp.com/find', {
"first_name": "Irinaa",
"last_name": "xyz",
"domain": "xyxz.com"
}).then((response) => {
if(response.status === 500){
console.log('no email found');
}
else {
console.log(response.data);
}
}, (error) => {
console.log('no email found ', i);
});
console.log('axios request done');
promises.push(request)
}
await Promise.all(promises)
}
Upvotes: 0
Reputation: 76
As you are in async function try using await instead of then. It will make your for loop behave synchronously.
let findEmail = async () => {
for (var i = 0; i < csvData.length; i++) {
try {
let response = await axios.post(
"https://email-finder.herokuapp.com/find",
{
first_name: "Irinaa",
last_name: "xyz",
domain: "xyxz.com"
}
);
if (response.status === 500) {
console.log("no email found");
} else {
console.log(response.data);
}
} catch (error) {
console.log("no email found ", i);
}
console.log("axios request done");
}
};
Upvotes: 3
Reputation: 1194
If you are waiting to get data back, so you are waiting to status 200. Try to add:
else if(response.status === 200){
console.log(response.data);
}
Upvotes: 0