Axios Inside For Loop
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 <
Solution 1:
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");
}
};
Solution 2:
Please find the explanation on How to await an async call in JavaScript in a synchronous function? here by T.J. Crowder.
Solution 3:
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);
}
Solution 4:
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)
}
Post a Comment for "Axios Inside For Loop"