1

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

Sumanth Jois
  • 97
  • 1
  • 7

4 Answers4

2

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");
      }
    };
0

Please find the explanation on How to await an async call in JavaScript in a synchronous function? here by T.J. Crowder.

Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
0

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);
    }
Ziv Ben-Or
  • 1,149
  • 6
  • 15
0

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)
} 
ccali11
  • 21
  • 3